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
1490
E
Accidental Victory
A championship is held in Berland, in which $n$ players participate. The player with the number $i$ has $a_i$ ($a_i \ge 1$) tokens. The championship consists of $n-1$ games, which are played according to the following rules: - in each game, two random players with non-zero tokens are selected; - the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly); - the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship. All random decisions that are made during the championship are made equally probable and independently. For example, if $n=4$, $a = [1, 2, 4, 3]$, then one of the options for the game (there could be other options) is: - during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $a = [0, 2, 4, 4]$; - during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $a = [0, 2, 8, 0]$; - during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $a = [0, 0, 10, 0]$; - the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players.
How can a player be checked if he can win the championship? Obviously, he must participate in all the games (otherwise we will increase the number of tokens of the opponents). So you can sort out all the people and play greedily with the weakest ones. Such a check will work in linear time after sorting, so we got a solution for $\mathcal{O}(n^2)$. The simplest solution to this problem is - binary search for the answer. We will sort all the players by the number of tokens they have. Let's prove that if player $i$ can win, then player $i+1$ can also win (the numbers are dealt after sorting). If the player $i$ was able to win, then based on the strategy above, he was able to defeat all the players on the prefix $[0 \ldots i+1]$. The player $i+1$ can also defeat all these players since he has at least as many tokens. Now both players have to defeat all opponents with numbers $[i+2 \ldots n]$ and the number of chips both players have is equal to the sum of the first $i+1$ numbers in the array. So if the player $i$ has a strategy, then the player $i+1$ can use the same strategy. Hence the answer to the problem is - sorted suffix of the input array. You can find this suffix using binary search and linear time checking. Bonus: this problem also has a fully linear (after sorting) solution.
[ "binary search", "data structures", "greedy" ]
1,400
def win(pos : int, a : list): power = a[pos] for i in range(len(a)): if i == pos: continue if power < a[i]: return False power += a[i] return True t = int(input()) while t > 0: t -= 1 n = int(input()) a = list(map(int, input().split(' '))) b = a.copy() a.sort() l = -1 r = n - 1 while r - l > 1: m = (l + r) // 2 if (win(m, a)): r = m else: l = m winIds = [] for i in range(n): if b[i] >= a[r]: winIds.append(i + 1) print(len(winIds)) print(*winIds)
1490
F
Equalize the Array
Polycarp was gifted an array $a$ of length $n$. Polycarp considers an array beautiful if there exists a number $C$, such that each number in the array occurs either zero or $C$ times. Polycarp wants to remove some elements from the array $a$ to make it beautiful. For example, if $n=6$ and $a = [1, 3, 2, 1, 4, 2]$, then the following options are possible to make the array $a$ array beautiful: - Polycarp removes elements at positions $2$ and $5$, array $a$ becomes equal to $[1, 2, 1, 2]$; - Polycarp removes elements at positions $1$ and $6$, array $a$ becomes equal to $[3, 2, 1, 4]$; - Polycarp removes elements at positions $1, 2$ and $6$, array $a$ becomes equal to $[2, 1, 4]$; Help Polycarp determine the minimum number of elements to remove from the array $a$ to make it beautiful.
Let's calculate the value of $cnt_x$ - how many times the number $x$ occurs in the array $a$. We will iterate over the value of $C$ and look for the minimum number of moves necessary for each number to appear in the $a$ array either $0$ times, or $C$ times. Note that if there is no such number $y$ that $cnt_y = C$, then such a value of $C$ will not give the minimum answer (because we have removed unnecessary elements). Then, for a specific $C$, the answer is calculated as follows: $\sum\limits_{cnt_x<C} cnt_x + \sum\limits_{cnt_x \ge C}(cnt_x - C)$ Since the number of candidates for the value of $C$ is no more than $n$, this method works in $\mathcal{O}(n^2)$. Then there are two ways to optimize our solution: you can consider only unique values of $C$ (there are no more than $\mathcal{O}(\sqrt n)$), and get a solution in $\mathcal{O}(n \sqrt n)$; you can sort the values $cnt_x$ and use prefix sums, this solution works for $\mathcal{O}(n \log n)$ or for $\mathcal{O}(n)$ (if you use counting sort).
[ "binary search", "data structures", "greedy", "math", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; map<int, int> cnt; for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x]++; } map<int, int> groupedByCnt; for (auto[x, y] : cnt) { groupedByCnt[y]++; } int res = n; int left = 0, right = n, rightCnt = (int) cnt.size(); for (auto[x, y] : groupedByCnt) { res = min(res, left + right - rightCnt * x); left += x * y; right -= x * y; rightCnt -= y; } cout << res << endl; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1490
G
Old Floppy Drive
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with $n$ integers written on it. Polycarp wrote the numbers from the disk into the $a$ array. It turned out that the drive works according to the following algorithm: - the drive takes one positive number $x$ as input and puts a pointer to the first element of the $a$ array; - after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the $a$ array, the last element is again followed by the first one; - as soon as the sum is at least $x$, the drive will shut down. Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you $m$ questions. To answer the $i$-th of them, you need to find how many seconds the drive will work if you give it $x_i$ as input. Please note that in some cases the drive can work infinitely. For example, if $n=3, m=3$, $a=[1, -3, 4]$ and $x=[1, 5, 2]$, then the answers to the questions are as follows: - the answer to the first query is $0$ because the drive initially points to the first item and the initial sum is $1$. - the answer to the second query is $6$, the drive will spin the disk completely twice and the amount becomes $1+(-3)+4+1+(-3)+4+1=5$. - the answer to the third query is $2$, the amount is $1+(-3)+4=2$.
Let's denote for $S$ the sum of all the elements of the array, and for $pref$ the array of its prefix sums. If the drive runs for $t$ seconds, the sum is $\left\lfloor \frac{t}{s} \right\rfloor \cdot S + pref[t \bmod n]$. This formula immediately shows that if $\max\limits_{i=0}^{n-1} pref[i] < x$ and $S \le 0$, then the disk will run indefinitely. Otherwise, the answer exists. The disk cannot make less than, $\left\lceil \frac{x - \max\limits_{i=0}^{n-1} pref[i]}{S} \right\rceil$ full spins, otherwise the required amount simply will not be achived. The disk can't make more spins either, because when it reaches the position of the maximum prefix sum, $x$ will already be achived. So we know how to determine the number of full spins of the disk. Let's make these spins: $x:= x - \left\lceil \frac{x - \max\limits_{i=0}^{n-1} pref[i]}{S} \right\rceil \cdot S$ Now we have a new problem, given $x$, find the first position $i$ in the array, such that $pref[i] \ge x$. This problem can be solved using binary search. If $pref$ is not sorted into the array, that is, there is $j$, such that $pref[j-1] > pref[j]$, then $pref[j]$ can simply be thrown out of the array (the answer will never be reached on it).
[ "binary search", "data structures", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n, m; cin >> n >> m; vector<ll> a(n); ll allSum = 0; vector<ll> pref; vector<int> ind; int curInd = 0; for (ll &e : a) { cin >> e; allSum += e; if (pref.empty() || allSum > pref.back()) { pref.push_back(allSum); ind.push_back(curInd); } curInd++; } for (int q = 0; q < m; q++) { ll x; cin >> x; if (pref.back() < x && allSum <= 0) { cout << -1 << " "; continue; } ll needTimes = 0; if (pref.back() < x) { needTimes = (x - pref.back() + allSum - 1) / allSum; } x -= needTimes * allSum; cout << needTimes * n + ind[lower_bound(pref.begin(), pref.end(), x) - pref.begin()] << " "; } cout << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1491
A
K-th Largest Value
You are given an array $a$ consisting of $n$ integers. \textbf{Initially all elements of $a$ are either $0$ or $1$}. You need to process $q$ queries of two kinds: - 1 x : Assign to $a_x$ the value $1 - a_x$. - 2 k : Print the $k$-th largest value of the array. As a reminder, $k$-th largest value of the array $b$ is defined as following: - Sort the array in the non-increasing order, return $k$-th element from it. For example, the second largest element in array $[0, 1, 0, 1]$ is $1$, as after sorting in non-increasing order it becomes $[1, 1, 0, 0]$, and the second element in this array is equal to $1$.
How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? How can we maintain $k$? Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \gets cnt - 1$. Otherwise, let $cnt \gets cnt + 1$. For the querys, just compare $cnt$ with $k$. If $cnt \ge k$, the answer will be $1$. Otherwise, the answer will be $0$. The complexity : $O(n + q)$.
[ "brute force", "greedy", "implementation" ]
800
n, q = map(int,input().split()) a = list(map(int,input().split())) zero = a.count(0) one = n - zero for _ in range(q): t, x = map(int,input().split()) if t == 1: if a[x-1] == 1: zero += 1 one -= 1 a[x-1] = 0 else: zero -= 1 one += 1 a[x-1] = 1 else: if x<=one: print(1) else: print(0)
1491
B
Minimal Cost
There is a graph of $n$ rows and $10^6 + 2$ columns, where rows are numbered from $1$ to $n$ and columns from $0$ to $10^6 + 1$: Let's denote the node in the row $i$ and column $j$ by $(i, j)$. Initially for each $i$ the $i$-th row has exactly one obstacle — at node $(i, a_i)$. You want to move some obstacles so that you can reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $u$ or $v$ coins, as below: - If there is an obstacle in the node $(i, j)$, you can use $u$ coins to move it to $(i-1, j)$ or $(i+1, j)$, if such node exists and if there is no obstacle in that node currently. - If there is an obstacle in the node $(i, j)$, you can use $v$ coins to move it to $(i, j-1)$ or $(i, j+1)$, if such node exists and if there is no obstacle in that node currently. - Note that you \textbf{can't move obstacles outside the grid}. For example, you can't move an obstacle from $(1,1)$ to $(0,1)$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph without passing through obstacles.
When is the answer $0$? Or rather, when do you not have to make any moves? What happens if $a[i]$ is same for all $i$? Consider the following situations: $\forall i \in [2,n], |a_i - a_{i - 1}| = 0$, then the answer will be $v + \min(u, v)$. $\exists i \in [2,n], |a_i - a_{i - 1}| > 1$, then the answer will be $0$. Otherwise, the answer will be $\min(u, v)$.
[ "brute force", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n, a[N], ans = INT_MAX, u, v, T; int main() { ios::sync_with_stdio(false); cin>>T; while(T--){ ans = INT_MAX; cin >> n >> u >> v; for(int i = 1; i <= n; i++) cin >> a[i]; for(int i = 2; i <= n; i++) { if(abs(a[i] - a[i - 1]) >= 2) ans = 0; if(abs(a[i] - a[i - 1]) == 1) ans = min(ans, min(u, v)); if(a[i] == a[i - 1]) ans = min(ans, v + min(u, v)); } cout << ans << endl; } return 0; }
1491
C
Pekora and Trampoline
There is a trampoline park with $n$ trampolines in a line. The $i$-th of which has strength $S_i$. Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice. If at the moment Pekora jumps on trampoline $i$, the trampoline will launch her to position $i + S_i$, and $S_i$ will become equal to $\max(S_i-1,1)$. In other words, $S_i$ will decrease by $1$, except of the case $S_i=1$, when $S_i$ will remain equal to $1$. If there is no trampoline in position $i + S_i$, then this pass is over. Otherwise, Pekora will continue the pass by jumping from the trampoline at position $i + S_i$ by the same rule as above. \textbf{Pekora can't stop jumping during the pass until she lands at the position larger than $n$ (in which there is no trampoline)}. Poor Pekora! Pekora is a naughty rabbit and wants to ruin the trampoline park by reducing all $S_i$ to $1$. What is the minimum number of passes she needs to reduce all $S_i$ to $1$?
Think greedily! By exchange argument, where can Pekora start her pass in an optimal solution? For a series of passes, we can describe it as an array $P$ where $P_i$ is the trampoline Pekora starts at in the $i$-th pass. We claim that the final state of trampolines after performing any permutation of $P$ will be the same. Focus on $2$ adjacent passes. We realize that if we swap those $2$ passes, the jumps done on both these passes are the same. Since swapping any $2$ adjacent passes does not change the final state of trampolines, any permutation of $P$ will not change the final state of trampolines. Now, we can claim that there is an optimal solution with $P$ being non-decreasing. Since Pekora can only move right, we must put Pekora on the first trampoline such that $S_i \ne 1$. However, we cannot directly simulate putting Pekora on the first trampoline such that $S_i \ne 1$. This actually uses $O(N^3)$. 5000 4999 4998 4997 ... 2 1 However, we can simulate this in $O(N^2)$ by the following. Instead of simulating passes individually, we will combine them. The main idea is that when Pekora jumps on a trampoline of strength $S_i$, we just add another Pekora on trampoline $S_i+i$ and process it later. So, when we process trampolines from $1$ to $N$, we keep track of how many Pekoras there are on trampoline $i$, which we will denote as $C_i$. Then, we only add extra Pekoras to trampoline $i$ if $S_i>C_i+1$. Now, we have some Pekoras on trampoline $i$ and we need to update other values of $C_i$. If $S_i=4$ and $C_i=6$ for example, we would add $1$ Pekora each trampolines to $i+2,i+3,i+4$ to reduce $S_i$ to 1. Then, the rest of the Pekoras will be moved to trampoline $i+1$. This algorithm runs in $O(N^2)$ as we only need to update $O(N)$ other trampolines at each step. Bonus: solve this problem in $O(N)$. (This was the original constraints but it was later changed since it was too hard for its position.)
[ "brute force", "data structures", "dp", "greedy", "implementation" ]
1,700
TC=int(input()) for tc in range(TC): n=int(input()) arr=list(map(int,input().split())) curr=[0]*(n+5) ans=0 for x in range(n): temp=curr[x] if (temp<arr[x]-1): ans+=arr[x]-1-temp temp+=arr[x]-1-temp curr[x+1]+=temp-arr[x]+1 for y in range(x+2,min(n,x+arr[x]+1)): curr[y]+=1 print(ans)
1491
D
Zookeeper and The Infinite Zoo
There is a new attraction in Singapore Zoo: The Infinite Zoo. The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled $1,2,3,\ldots$. There is a directed edge from vertex $u$ to vertex $u+v$ if and only if $u\&v=v$, where $\&$ denotes the bitwise AND operation. There are no other edges in the graph. Zookeeper has $q$ queries. In the $i$-th query she will ask you if she can travel from vertex $u_i$ to vertex $v_i$ by going through directed edges.
Since $\&$ is a bitwise operation, represent the number in binary form! We can convert any $u+v$ move to a series of $u+v'$ moves where $u\&v'=v'$ and $v'=2^k$. Such a move converts a substring of the binary string of the form $01\ldots11$ into $10\ldots00$. Focus on converting $01$ into $10$. Firstly, we can show that the reachability graph is equivalent if we restrict to a directed edge between vertices $u$ and $u+v$ if $u\&v=v$ and that $v=2^k$ for some $k$. This is because we can add each bit from $v$ from $u$ from the highest bit as adding a bit to a number will not affect lower bits. Now, we observe that such as operation converts a binary string of the form $01\ldots11$ into $10\ldots00$ for some substring when we represent $u$ as a binary string. (more significant bits are to the left). Now, we consider $s$ and $t$ as binary strings. If and only if there is a matching from bits in $t$ to a lower bit in $s$ and $t$ > $s$, then $t$ is reachable from $s$. Turning $01\ldots11$ into $10\ldots00$ means that we can move a bit ($01$->$10$) or we can squish multiple bits ($0111$->$1000$). Let us show it is necessary. If $s>t$, it is impossible. And if there is no such matching, we are not able to put a position in $t$ as bits cannot move back, or there are not enough bits in $s$ to form $t$ (since the number of bits cannot increase). Let is show it is sufficient. Since $s<t$ ($s=t$ is trivial), the strings have some common prefix and the most significant different bit has $0$ in $s$ and $1$ and $t$. Now, we can shift every bit in s into a position in t and squish the most significant bits. To check if there is a matching, we find the least significant bit ($lsb$) of $t$ and $s$. if $lsb(t) < lsb(s)$ or if $s = 0$, then it is impossible. Else, we remove the $lsb$ from both $t$ and $s$ and repeat. If we're able to remove bits until $t=0$, then it is possible to go from $s$ to $t$.
[ "bitmasks", "constructive algorithms", "dp", "greedy", "math" ]
1,800
def lsb(x): return x & (-x) Q = int(input()) for q in range(Q): a,b = map(int,input().split(" ")) if a > b: print("NO") else: can = True while b > 0: if lsb(b) < lsb(a) or a == 0: can = False break a -= lsb(a) b -= lsb(b) print("YES" if can else "NO")
1491
E
Fib-tree
Let $F_k$ denote the $k$-th term of Fibonacci sequence, defined as below: - $F_0 = F_1 = 1$ - for any integer $n \geq 0$, $F_{n+2} = F_{n+1} + F_n$ You are given a tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles. We call a tree a \textbf{Fib-tree}, if its number of vertices equals $F_k$ for some $k$, and at least one of the following conditions holds: - The tree consists of only $1$ vertex; - You can divide it into two Fib-trees by removing some edge of the tree. Determine whether the given tree is a Fib-tree or not.
The only pair $(j,k)$ that satisfies $F_i=F_j+F_k$ is $(i-1,i-2)$. Firstly, we can discover that we can only cut a tree in the size of $f_{i}$ into one in size of $f_{i-1}$ and one in size of $f_{i-2}$. We want to show that the only solution to $F_i=F_j+F_k$ is $(j,k)=(i-1,i-2)$ for $j \geq k$. Clearly, $i>j$, otherwise, $F_i<F_j+F_k$. Furthermore, $j>i-2$ as $F_i>2 \cdot F_{i-2}$. Therefore, we have shown the only solution is $(j,k)=(i-1,i-2)$. However, we will have 2 ways to partition the tree sometimes. But it turns out we can cut any edge! We will prove that if some edge cuts Fib-tree of $F_n$ vertices into trees with sizes $F_{n-1}$ and $F_{n-2}$, we can cut it, and the resulting trees are also Fib-trees. By induction. For $n = 2$ it's obvious. If only edge cuts Fib-tree into trees with sizes $F_{n-1}$ and $F_{n-2}$, we have to cut it. If there are two such edges: suppose that cutting the first edge results in making two Fib-trees. Then in the tree of size $F_{n-1}$ the second edge divides it into trees of sizes $F_{n-2}$ and $F_{n-3}$, so we can cut it as well in the next step. But then we could as well cut the second edge first: we will have one Fib-tree of size $F_{n-2}$, and one tree of size $F_{n-1}$ which is cut into Fib-trees of sizes $F_{n-2}$ and $F_{n-3}$ by the first edge, so it's also a Fib-tree! Because the growth of Fibonacci sequence is approximately $O(\phi^n)$, we only need to cut our tree $O(\log_\phi n)$ times: every time, if we find the splitting edge, we cut it, and recurse to the resulting trees, if at some point there was no splitting edge - tree isn't Fib-tree. Finally, we got an $O(n\log_\phi n)$ solution.
[ "brute force", "dfs and similar", "divide and conquer", "number theory", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, siz[N]; vector<int> fib; vector<pair<int, bool> > G[N]; void NO() { cout << "NO\n"; exit(0); } void GetSize(int u, int fa) { siz[u] = 1; for(pair<int, bool> e : G[u]) { if(e.second) continue; int v = e.first; if(v == fa) continue; GetSize(v, u); siz[u] += siz[v]; } } void CutEdge(int u, int fa, int k, int &pu, int &pv, int &kd) { for(pair<int, bool> e : G[u]) { if(pu) return; if(e.second) continue; int v = e.first; if(v == fa) continue; if(siz[v] == fib[k - 1] || siz[v] == fib[k - 2]) { pu = u; pv = v; kd = (siz[v] == fib[k - 1]) ? k - 1 : k - 2; break; } CutEdge(v, u, k, pu, pv, kd); } } void Check(int u, int k) { // cout << "Check " << u << ' ' << k << endl; if(k <= 1) return; GetSize(u, 0); int pu = 0, pv = 0, kd = 0; CutEdge(u, 0, k, pu, pv, kd); // cout << pu << ' ' << pv << ' ' << kd << endl; if(!pu) NO(); for(pair<int, bool> &e : G[pu]) if(e.first == pv) e.second = true; for(pair<int, bool> &e : G[pv]) if(e.first == pu) e.second = true; Check(pv, kd); Check(pu, (kd == k - 1) ? k - 2 : k - 1); } int main() { ios::sync_with_stdio(false); cin >> n; fib.push_back(1); fib.push_back(1); for(int i = 1; ; i++) { if(fib[i] >= n) break; int new_fib = fib[i] + fib[i - 1]; fib.push_back(new_fib); } for(int i = 1; i < n; i++) { int u, v; cin >> u >> v; G[u].push_back(make_pair(v, false)); G[v].push_back(make_pair(u, false)); } if(fib[fib.size() - 1] != n) NO(); Check(1, fib.size() - 1); cout << "YES\n"; return 0; }
1491
F
Magnets
This is an interactive problem. Kochiya Sanae is playing with magnets. Realizing that some of those magnets are demagnetized, she is curious to find them out. There are $n$ magnets, which can be of the following $3$ types: - N - S - - — these magnets are demagnetized. Note that \textbf{you don't know} the types of these magnets beforehand. You have a machine which can measure the force between the magnets, and you can use it \textbf{at most} $n+\lfloor \log_2n\rfloor$ times. You can put some magnets to the left part of the machine and some to the right part of the machine, and launch the machine. Obviously, you can put one magnet to at most one side (you don't have to put all magnets). You can put the same magnet in different queries. Then the machine will tell the force these magnets produce. Formally, let $n_1,s_1$ be the number of N and S magnets correspondently on the left and $n_2,s_2$ — on the right. Then the force between them would be $n_1n_2+s_1s_2-n_1s_2-n_2s_1$. Please note that the force is a \textbf{signed} value. However, when the \textbf{absolute} value of the force is \textbf{strictly larger than} $n$, the machine will crash into pieces. You need to find \textbf{all} magnets of type - (all demagnetized ones), \textbf{without breaking the machine}. \textbf{Note that the interactor is not adaptive}. The types of the magnets are fixed before the start of the interaction and do not change with queries. It is guaranteed that there are \textbf{at least} $2$ magnets whose type is not -, and \textbf{at least} $1$ magnet of type -.
Try to construct a solution that works in $2n$ queries. Try to find the second magnet which is not `-'. The actual query limit is $n-1+\lceil\log_2n\rceil$. It seems this problem needs some random technique, but here is a determinate solution: We just try to find a not demagnetized magnet. You can go through the following method to find one: First put the first magnet in the left. Then ask all the other magnets with the left pile. If we got a non-zero answer, we find a valid magnet; else we just put this magnet in the left. It can be proven later that we will always be able to find a valid magnet. Then use this magnet to try on all other magnets. This process form a solution requiring at most $2n-2$ queries. However, when we look back at this solution we'll realize that there is a huge waste of information in the previous queries. As all the previous answers are $0$, it's easy to prove that the magnet we found is the second one we have selected. Since we know nothing about the right part, we can simply check the magnets in the right one by one. However, you have known that there is only $1$ magnetic magnet in the left, so you can do a binary search to seek for the answer. The maximum number of queries is $n-1+\lceil\log_2n\rceil$, which perfectly matches the limit.
[ "binary search", "constructive algorithms", "interactive" ]
2,700
#include<bits/stdc++.h> int n; std::vector<int>ans,tmp,hlf; int main() { int T; scanf("%d",&T); for(;T--;) { ans.clear(),tmp.clear(),hlf.clear(); scanf("%d",&n); register int i,ii; int sec=0; for(i=2;i<=n;i++) { printf("? 1 %d\n%d\n",i-1,i); for(ii=1;ii<i;ii++)printf("%d ",ii); puts(""),fflush(stdout); int f; scanf("%d",&f); if(f){sec=i;break;} }for(i=sec+1;i<=n;i++) { printf("? 1 1\n%d\n%d\n",sec,i); fflush(stdout); int f; scanf("%d",&f); if(!f)ans.push_back(i); }for(i=1;i<sec;i++)tmp.push_back(i); while(tmp.size()>1) { int md=tmp.size()>>1; hlf.clear(); for(i=1;i<=md;i++) hlf.push_back(tmp.back()),tmp.pop_back(); printf("? 1 %d\n%d\n",md,sec); for(int t:hlf)printf("%d ",t); puts(""),fflush(stdout); int f; scanf("%d",&f); if(f)tmp=hlf; } for(i=1;i<sec;i++)if(tmp[0]!=i)ans.push_back(i); printf("! %u",ans.size()); for(int t:ans)printf(" %d",t); puts(""),fflush(stdout); } }
1491
G
Switch and Flip
There are $n$ coins labeled from $1$ to $n$. Initially, coin $c_i$ is on position $i$ and is facing upwards (($c_1, c_2, \dots, c_n)$ is a permutation of numbers from $1$ to $n$). You can do some operations on these coins. In one operation, you can do the following: - Choose $2$ distinct indices $i$ and $j$. - Then, swap the coins on positions $i$ and $j$. - Then, flip both coins on positions $i$ and $j$. (If they are initially faced up, they will be faced down after the operation and vice versa) Construct a sequence of at most $n+1$ operations such that after performing all these operations the coin $i$ will be on position $i$ at the end, \textbf{facing up}. Note that you \textbf{do not need} to minimize the number of operations.
Visualize this problem as graph with directed edges $(i,c_i)$. Solve this problem where there is only $1$ big cycle. What if a cycle has $2$ coins that are upside down? How can we force a cycle into such state? We can visualize the problem as a graph with nodes of $2$ colors (face up - red and face down - blue). Initially, the graph has nodes with all red color and with a directed edge to $c_i$. Firstly, any $2$ cycles with all red nodes can be converted into a single cycle with $2$ blues nodes with $1$ swap. A cycle with $2$ blue nodes is very convenient here as swapping a blue node with a red node it is pointing to will decrease the cycle size and maintain that the cycle still has $2$ blue nodes. We can keep decreasing the cycle size until the cycle has only $2$ blue nodes and solve that in $1$ swap. Thus, solving $2$ cycles which have $X$ nodes in total uses only $X$ swaps. Now, we simply pair the cycles and do this. However, if there is an odd number of cycles, there are $2$ cases: If the cycle does not cover the whole graph, we can solve the remaining cycle and a cycle of size $1$ together. Otherwise, we can force $2$ blue nodes into the cycle with $2$ swaps (does not work for $n = 2$ so be careful). Both cases need $X+1$ moves where $X$ is the size of the remaining cycle. Thus, at most $X+1$ swaps is needed in this algorithm.
[ "constructive algorithms", "graphs", "math" ]
2,800
from sys import stdin, stdout n=int(stdin.readline()) #make 1-indexed arr=[0]+list(map(int,stdin.readline().split())) vis=[0]*(n+1) ans=[] def cswap(i,j): arr[i],arr[j]=-arr[j],-arr[i] ans.append((i,j)) def swap_cyc(i,j): cswap(i,j) curr=i while (arr[-arr[curr]]>0): cswap(curr,-arr[curr]) curr=-arr[curr] while (arr[-arr[curr]]>0): cswap(curr,-arr[curr]) cswap(curr,-arr[curr]) p=-1 for i in range(1,n+1): if (vis[i]==1): continue if (arr[i]==i): continue curr=i while (True): vis[curr]=1 curr=arr[curr] if (curr==i): break if (p==-1): p=i else: swap_cyc(p,i) p=-1 if (p!=-1): can=False for i in range(1,n+1): if (arr[i]==i): swap_cyc(p,i) can=True break if (can==False): t1,t2=arr[p],arr[arr[p]] cswap(p,t1) swap_cyc(t1,t2) print(len(ans)) [print(i[0],i[1]) for i in ans]
1491
H
Yuezheng Ling and Dynamic Tree
Yuezheng Ling gives Luo Tianyi a tree which has $n$ nodes, rooted at $1$. Luo Tianyi will tell you that the parent of the $i$-th node is $a_i$ ($1 \leq a_i<i$ for $2 \le i \le n$), and she will ask you to perform $q$ queries of $2$ types: - She'll give you three integers $l$, $r$ and $x$ ($2 \le l \le r \le n$, $1 \le x \le 10^5$). You need to replace $a_i$ with $\max(a_i-x,1)$ for all $i$ with $l \leq i \leq r$. - She'll give you two integers $u$, $v$ ($1 \le u, v \le n$). You need to find the LCA of nodes $u$ and $v$ (their lowest common ancestor).
The complexity is $\mathcal O(n\sqrt{n})$. Divide the nodes into $\sqrt{n}$ blocks. The $i$-th block will contain the nodes in $[(i-1) \sqrt{n}+1,i \sqrt{n}]$. Let's define $f_x$ as an ancestor of $x$ such that $f_x$ is in the same block as $x$ and $a_{f_x}$ is not in the same block as $x$. Notice that for a given block, if all $a_x$ is not in the same block as $x$, then $f_x=x$. So, we do not have to re-compute all values of $f_x$ for a certain block if $\forall x, x-a_x \geq \sqrt n$ in this block. When we update a range, we will update some ranges fully and update at most $2$ ranges partially. Let's show that only $O(n+q)$ re-computations will happen. For a certain block, if it is completely contained in an update, the value of $x-a_x$ will increase by $1$, a single block will be re-computed by at most $O(\sqrt n)$ of such updates, which will contribute $O(\sqrt n \cdot \sqrt n)=O(n)$ re-computations. For blocks that are partially updated by an update, such things will only happen at most $2q$ times, therefore we have a bound of $O(q)$ re-computations from such updates. Maintaining $f_x$, querying can be easily done in $O(\sqrt n)$.
[ "data structures", "trees" ]
3,400
#include <bits/stdc++.h> #define N 100005 using namespace std; template <typename T> void read(T &a) { T x = 0,f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } a = x * f; } template <typename T> void write(T x) { if (x < 0) putchar('-'),x = -x; if (x < 10) return (void) putchar(x + '0'); write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); putchar('\n'); } template <typename T> void writes(T x) { write(x); putchar(' '); } template <typename T,typename... Args> void read(T &maxx,Args &... args) { read(maxx); read(args...); } template <typename T,typename... Args> void writeln(T maxx,Args ... args) { writes(maxx); writes(args...); putchar('\n'); } const int B = 300; int n,q,a[N],num,bl[N],vis[N]; std::vector<int> v; struct Block { int f[B],lazy,flag,cnt,L,R; void update() { flag = 1; for (int i = L; i <= R; i++) { if (bl[i] != bl[a[i]]) f[i - L] = i; else f[i - L] = f[a[i] - L],flag = 0; } } void update(int l,int r,int x) { for (int i = l; i <= r; i++) a[i] = i == 1 ? 0 : max(a[i] - x,1); update(); } void update(int x) { if (flag) lazy += x; else update(L,R,x); } }T[(N - 1) / B + 5]; void update(int l,int r,int x) { if (bl[l] == bl[r]) { T[bl[l]].update(l,r,x); return ; } T[bl[l]].update(l,T[bl[l]].R,x); for (int i = bl[l] + 1; i < bl[r]; i++) T[i].update(x); T[bl[r]].update(T[bl[r]].L,r,x); // cout << l << ' ' << r << ' ' << x << endl; // cout << '0' << ' '; // for (int i = 2; i <= n; i++) // cout << max(a[i] - T[bl[i]].lazy,1) << ' '; // cout << endl; } void clear() { for (int i = 0; i < v.size(); i++) vis[v[i]] = 0; v.clear(); } int query(int x,int y) { // cout << '0' << ' '; // for (int i = 2; i <= n; i++) // cout << max(a[i] - T[bl[i]].lazy,1) << ' '; // cout << endl; while (T[bl[x]].f[x - T[bl[x]].L] != T[bl[y]].f[y - T[bl[y]].L]) { if (bl[x] < bl[y]) swap(x,y); // cout << x << ' ' << T[bl[x]].f[x - T[bl[x]].L] << endl; x = (T[bl[x]].f[x - T[bl[x]].L] == 1) ? 0 : max(a[T[bl[x]].f[x - T[bl[x]].L]] - T[bl[x]].lazy,1); } int qaq = (T[bl[x]].f[x - T[bl[x]].L] == 1) ? 0 : max(a[T[bl[x]].f[x - T[bl[x]].L]] - T[bl[x]].lazy,1); while (x != qaq) { assert(x != qaq); vis[x] = 1; v.push_back(x); x = (x == 1) ? 0 : max(a[x] - T[bl[x]].lazy,1); } while (y != qaq) { if (vis[y]) return clear(),y; y = (y == 1) ? 0 : max(a[y] - T[bl[y]].lazy,1); } } signed main() { read(n,q); for (int i = 2; i <= n; i++) read(a[i]); num = (n - 1) / B + 1; for (int i = 1; i <= num; i++) { T[i].L = (i - 1) * B + 1; T[i].R = min(i * B,n); T[i].cnt = i * B - (i - 1) * B; T[i].flag = T[i].lazy = 0; for (int j = T[i].L; j <= T[i].R; j++) bl[j] = i; } for (int i = 1; i <= num; i++) T[i].update(); while (q--) { int opt; read(opt); if (opt == 1) { int l,r,x; read(l,r,x); update(l,r,x); } if (opt == 2) { int u,v; read(u,v); writeln(query(u,v)); } } // cerr << (double) clock() / CLOCKS_PER_SEC << endl; return 0; }
1491
I
Ruler Of The Zoo
After realizing that Zookeeper is just a duck, the animals have overthrown Zookeeper. They now have to decide a new ruler among themselves through a fighting tournament of the following format: Initially, animal $0$ is king, while everyone else queues up with animal $1$ at the front of the queue and animal $n-1$ at the back. The animal at the front of the queue will challenge the king to a fight, and the animal with greater strength will win the fight. The winner will become king, while the loser joins the back of the queue. An animal who \textbf{wins $3$ times consecutively} will be crowned ruler for the whole zoo. The strength of each animal depends on how many consecutive fights he won. Animal $i$ has strength $A_i$ with $0$ consecutive win, $B_i$ with $1$ consecutive win, and $C_i$ with $2$ consecutive wins. Initially, everyone has $0$ consecutive win. \textbf{For all animals, $A_i > B_i$ and $C_i > B_i$}. Also, the values of $A_i$, $B_i$, $C_i$ are \textbf{distinct} (all $3n$ values are pairwise different). In other words, an animal who is not a king has strength $A_i$. A king usually has a strength of $B_i$ or $C_i$. The exception is on the first turn, the first king (animal $0$) has strength $A_i$. Who is the new ruler, and after how many fights? Or will it end up that animals fight forever with no one ending up as ruler?
As the solution to this problem is very long, the full editorial is split into $4$ parts. If you want to challenge yourself, you can try reading one part at a time and see if you get any inspiration. You can also try to read the specific hints for each part. Convert the queue into a circle. Firstly, let's convert the queue into a circle. In our new problem, $n$ animals stand in a circle. The king fights the animal directly clockwise to it. If the king wins, he and the other person swap places, otherwise nothing happens. The animal that is king will always move 1 space clockwise regardless of what happens. For example, in this scenario, 0 beats 1, so he stays as king. But he then loses to 2. Call animals whose A is smaller than the B of the animal before them RED color and the rest of the animals NONRED color. Work out the inequalities. How do the colors of animals change? Let's give each animal a color. An animal $i$ is RED if $B_{i-1}$ > $A_i$. In other words, and animal is red if and only if the previous animal will beat it as king. The animals that are not red are called NONRED for now. We can assume no two animals are consecutively RED* (*will elaborate more in part 4). Suppose we have 3 animals $XYZ$ in that order, and $Y$ is red while $X$ and $Z$ are non-red. Suppose $X$ becomes king and wins $Y$ but not $Z$. As such, the final arrangement is $YXZ$. The claim here is that $X$ and $Z$ cannot become RED. For $X$, $X$ beats $Y$, We have $B_X > A_Y$, but since $A_X > B_X$ and $A_Y > B_Y$, we get that $B_Y < A_X$. As such, $X$ cannot be RED. For $Z$, we have $C_X < A_Z$ (since X lost to Z) and $B_X < C_X$, we hence have $B_X < A_Z$. As such, $Z$ cannot be RED Finally for $Y$, it is possible that it turns from RED to NONRED. From these we can conclude that RED cannot be created, but can be destroyed. REDs can only be destroyed at most $O(n)$ times. Simulate a lot "uneventful" moves at once. Consider NONRED positions to be fixed, and the REDs rotate anti-clockwise about them. After $n-1$ moves, what do you observe? Do many sets of $n-1$ moves at once until a RED is destroyed or when the game ends. How to find when a RED is destroyed or when the game ends event occurs quickly? As such, we have the following conclusions: REDS are never created only destroyed The order of NONREDS will not change unless a RED inserts itself within the sequence REDS will never battle REDS (because of * assumption) Since the number of times REDS can be destroyed is limited, we should exploit that. We define an event as either when a RED is destroyed or when the game ends. Since events can occur at most $O(n)$ times, we just need to find some way to quickly simulate the moves until the next event. Let's visualize the moves like this: instead of the RED and NONRED swapping positions, the NONREDs are fixed in position, and the REDs move around anticlockwise. After $n-1$ moves, every RED moves one space anticlockwise around the belt of NONREDs Then in that case, we just need to check how many sets of $n-1$ moves is needed until the first event occurs. For convenience, let's split NONRED into BLUE and GREEN. If a NONRED beats a red in front of it, and it loses to next animal, then it is BLUE. If it wins one more time (and hence the entire game) it is GREEN. Let's look at the conditions for the events: A RED is destroyed. This occurs when $B_{nr} < A_{r}$ where $nr$ is any BLUE or GREEN The game ends. This occurs when $B_{g} > A_{r}$ where $g$ is any GREEN To find the first how many times the reds need to move anticlockwise, we could maintain a monotonic vector across the belt of NONREDs, and then for each RED, binary search the earliest position where an event occurs. Finally, when we find the number of sets of $n-1$ we need to move backwards, we move everything manually, check if the game ends. Then we recompute the color of all animals, and repeat. If no event occurs, then it will repeat infinitely. The step of finding the number of steps before first event occurs takes $O(nlogn)$ in total. Since REDs can disappear at most $O(n)$ times, then the total time complexity is $O(n^2logn)$. It's worth noting that the constant factor for this algorithm is small as the number of REDs is $0.5n$ and binary search is a very fast log. Hence, it passes quite comfortably (author's solution is under 400ms) even though $n \leq 6000$. In terms of implementation, we can run the first $2n$ by brute force just to handle some bad corner cases. In particular, it is mostly to handle the assumption "We can assume no two animals are consecutively RED". If two animals are consecutively RED, then working out the inequalities will show that the one right before the two REDs should be able to win, and hence the game should end within $2n$ moves.
[ "brute force", "data structures" ]
3,500
//雪花飄飄北風嘯嘯 //天地一片蒼茫 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define ll long long #define ii pair<ll,ll> #define iii pair<ii,ll> #define fi first #define se second #define endl '\n' #define debug(x) cout << #x << " is " << x << endl #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #define lb lower_bound #define up upper_bound #define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--)) #define all(x) (x).begin(),(x).end() #define sz(x) (int)(x).size() #define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> //change less to less_equal for non distinct pbds, but erase will bug mt19937 rng(chrono::system_clock::now().time_since_epoch().count()); struct dat{ int a,b,c; int idx; }; int n; dat head; deque<dat> dq; dat state[6005]; dat trans_belt[6005]; bool green[6005]; int curr; ll moves=1; void brute(){ rep(x,0,1000000){ if ((curr==0?head.a:(curr==1?head.b:head.c))>dq.front().a){ dq.pub(dq.front()); dq.pof(); curr++; if (curr==3){ cout<<head.idx<<" "<<moves<<endl; exit(0); } } else{ dq.pub(head); head=dq.front(); dq.pof(); curr=1; } moves++; if (x>n && curr==1) break; } } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin.exceptions(ios::badbit | ios::failbit); cin>>n; rep(x,0,n){ int a,b,c; cin>>a>>b>>c; if (!x) head={a,b,c,x}; else dq.pub({a,b,c,x}); } curr=0; brute(); //convert to state state[0]=head; rep(x,1,n) state[x]=dq[x-1]; while (true){ //cout<<"move: "<<moves-1<<endl; //rep(x,0,n) cout<<state[x].idx<<" "; cout<<endl; vector<ii> stk; //find the first instance where state[z].b<state[x].a //maintain min stack of state[z].b //now, we focus on the belt itself //there is a case where the red does not convert to a anything but the game ends //we need to handle that case carefully! //i think lets just insert it into stack with value -1 //then if it appears its easily handled memset(green,false,sizeof(green)); int cnt=0; int pidx=-1; rep(x,0,n){ if (x && state[x-1].b>state[x].a){ //red } else{ //not red if (pidx!=-1 && state[pidx].c>state[x].a){ green[pidx]=true; } pidx=x; } } if (state[pidx].c>state[0].a) green[0]=true; rep(x,0,n){ if (x && state[x-1].b>state[x].a){ //red } else{ //not red int temp=green[x]?-1:state[x].b; while (!stk.empty() && stk.back().fi>temp) stk.pob(); stk.pub(ii(temp,cnt)); cnt++; } } int best=1e9; //shortest distance until red becomes not red int cnt2=cnt; //cout<<"non-reds: "<<cnt<<endl; rep(x,0,n){ if (x && state[x-1].b>state[x].a){ //red if (stk.front().fi>state[x].a) continue; //it wont become red here int lo=0,hi=sz(stk),mi; while (hi-lo>1){ mi=hi+lo>>1; if (stk[mi].fi<state[x].a) lo=mi; else hi=mi; } //cout<<"debug: "<<x<<endl; //for (auto &it:stk) cout<<it.fi<<"_"<<it.se<<" "; cout<<endl; //cout<<state[x].a<<endl; //cout<<"found: "<<pos[stk[hi]]<<endl; int dist=cnt2-stk[lo].se; //cout<<dist<<endl; if (dist<best){ best=dist; } //cout<<endl; } else{ //not red int temp=green[x]?-1:state[x].b; while (!stk.empty() && stk.back().fi>temp) stk.pob(); stk.pub(ii(temp,cnt2)); cnt2++; } } //cout<<"number in belt: "<<cnt<<endl; //cout<<"d: "<<best<<" "<<idx<<endl; if (best==1e9){ cout<<"-1 -1"<<endl; return 0; } //we simulate best-1 cycles for the reds best--; //cout<<"hmm: "<<endl; //cout<<best<<" "<<cnt<<endl; if (best>=0){ moves+=best*(n-1); //cout<<endl; cnt2=0; rep(x,0,n){ if (x && state[x-1].b>state[x].a){ //red } else{ //not red trans_belt[cnt2]=state[x]; cnt2++; } } //rep(x,0,cnt2) cout<<trans_belt[x].idx<<" "; cout<<endl; rep(x,n,0){ if (x && state[x-1].b>state[x].a){ //red } else{ //not red cnt2--; //cout<<x<<" "<<(cnt2-best+cnt)%cnt<<endl; state[x]=trans_belt[(cnt2-best+cnt)%cnt]; } } } //cout<<cnt<<endl; //cout<<"move: "<<moves-1<<endl; //rep(x,0,n) cout<<state[x].idx<<" "; cout<<endl; head=state[0]; dq.clear(); rep(x,1,n) dq.pub(state[x]); curr=1; brute(); //convert to state state[0]=head; rep(x,1,n) state[x]=dq[x-1]; //cout<<"move: "<<moves-1<<endl; //rep(x,0,n) cout<<state[x].idx<<" "; cout<<endl; //cout<<endl; //break; } }
1492
A
Three swimmers
Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool. It takes the first swimmer exactly $a$ minutes to swim across the entire pool and come back, exactly $b$ minutes for the second swimmer and $c$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $0$, $a$, $2a$, $3a$, ... minutes after the start time, the second one will be at $0$, $b$, $2b$, $3b$, ... minutes, and the third one will be on the left side of the pool after $0$, $c$, $2c$, $3c$, ... minutes. You came to the left side of the pool exactly $p$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.
The answer is just $\min{(\lceil {p \over a} \rceil \cdot a, \lceil {p \over b} \rceil \cdot b, \lceil {p \over c} \rceil \cdot c)} - p$. Complexity: $O(1)$.
[ "math" ]
800
null
1492
B
Card Deck
You have a deck of $n$ cards, and you'd like to reorder it to a new one. Each card has a value between $1$ and $n$ equal to $p_i$. All $p_i$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $p_1$ stands for the bottom card, $p_n$ is the top card. In each step you pick some integer $k > 0$, take the top $k$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.) Let's define an order of a deck as $\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$. Given the original deck, output the deck with maximum possible order you can make using the operation above.
It's easy to prove that order of a deck differs for different permutations. And more than that order of permutation $a$ is greater than order of permutation $b$ if and only if $a$ is lexicographically greater than $b$. Since we need to build a lexicographic maximum permutation, at each point of time we need to choose such $k$ that $k$-th element from the top of the original deck is the maximum element in this deck. Total complexity is $O(n \log n)$ or $O(n)$ (depending on the implementation).
[ "data structures", "greedy", "math" ]
1,100
null
1492
C
Maximum width
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $s$ of length $n$ and $t$ of length $m$. A sequence $p_1, p_2, \ldots, p_m$, where $1 \leq p_1 < p_2 < \ldots < p_m \leq n$, is called beautiful, if $s_{p_i} = t_i$ for all $i$ from $1$ to $m$. The width of a sequence is defined as $\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$. Please help your classmate to identify the beautiful sequence with the \textbf{maximum width}. Your classmate promised you that for the given strings $s$ and $t$ there is at least one beautiful sequence.
For some subsequence of the string $s$, let $p_i$ denote the position of the character $t_i$ in the string $s$. For fixed $i$, we can find a subsequence that maximizes $p_{i + 1} - p_i$. Let $\textit{left}_{i}$ and $\textit{right}_{i}$ be the minimum and maximum possible value of $p_i$ among all valid $p$s. Now, it is easy to see that the maximum possible value of $p_{i+1} - p_{i}$ is equal to $\textit{right}_{i + 1} - \textit{left}_{i}$. To calculate $\textit{left}_i$ we just need to find the first element after $\textit{left}_{i - 1}$ which is equal to $t_i$. This can be done by a simple greedy or dp algorithm. $\textit{right}_i$ can be found in the same way. So, after finding $\textit{left}$ and $\textit{right}$, the answer is $\max_{i=1}^{i=n-1} \textit{right}_{i + 1} - \textit{left}_i$. Complexity: $O(n + m)$.
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
1,500
null
1492
D
Genius's Gambit
You are given three integers $a$, $b$, $k$. Find two binary integers $x$ and $y$ ($x \ge y$) such that - both $x$ and $y$ consist of $a$ zeroes and $b$ ones; - $x - y$ (also written in binary form) has exactly $k$ ones. You are \textbf{not allowed to use leading zeros for $x$ and $y$}.
This problem has a cute constructive solution. If $a = 0$ or $b = 1$ the answer is trivial. In other cases let's fix $x$ as a number in form $111 \ldots 1100 \ldots 000$. Let $y = x$, then we will change only $y$. Let's take the last $1$ digit from the consecutive prefix of ones, then move it $\min(k, a)$ positions to the right. It is easy to see, that the number of ones in $x - y$ has increased by $\min(k, a)$. If $k \leq a$ we already have the answer. If not, let's take the last $1$ digit from the consecutive prefix of ones and move it one position to the right. The number of ones in the answer increased by one and if it is less than $k$, we just repeat this move. With this construction we can easily build an answer for every $k \leq a + b - 2$ It's not difficult to prove that the answer does not exist when $k > a + b - 2$.
[ "bitmasks", "constructive algorithms", "greedy", "math" ]
1,900
null
1492
E
Almost Fault-Tolerant Database
You are storing an integer array of length $m$ in a database. To maintain internal integrity and protect data, the database stores $n$ copies of this array. Unfortunately, the recent incident may have altered the stored information in every copy in the database. It's believed, that the incident altered at most two elements in every copy. You need to recover the original array based on the current state of the database. In case there are multiple ways to restore the array, report any. If there is no array that differs from every copy in no more than two positions, report that as well.
Let's look at the first array. Every possible answer (if there is any) should not differ from this array in more than $2$ positions. So we should try to change at most $2$ positions in the first array to find a consistent answer. Let's look at the other arrays. We can ignore each other array that differ with the first array in no more than $2$ positions. In particular, if every array doesn't differ in more than $2$ position, we can just print the first array as an answer. If an array differs in $5$ (or more) positions, then no answer exists. Suppose that we selected an array with $3$ or $4$ diffs. This means that we must change $1$ or $2$ positions (respectively) in the first array to reduce it to $2$ diffs. We have $3$ or $6$ ways to do this (respectively), and can go through all the options. After changing, we should look at all arrays again and make changes in the first array again if required (but no more than in $2$ positions in total) in a recursive backtracking manner. If we don't get an answer, we should go back and try another option. The time complexity is $O(n \cdot m)$ with a decent constant. Bonus1: If allowed number of diffs is $k$, can you solve problem in $O(k^knm)$ time? Bonus2: If allowed number of diffs is $k$, can you solve problem in $O(nm + k^k \sqrt{nm})$ time?
[ "brute force", "constructive algorithms", "dfs and similar", "greedy", "implementation" ]
2,500
null
1493
A
Anti-knapsack
You are given two integers $n$ and $k$. You are asked to choose maximum number of distinct integers from $1$ to $n$ so that there is no subset of chosen numbers with sum equal to $k$. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.
Let's notice that we can take all numbers $k+1, k+2 \ldots n$, because every one of them is greater than $k$, and sum of any number from $k+1, k+2 \ldots n$ and any number from $1,2 \ldots n$ also is greater than $k$. Let's also take numbers from $\left \lceil \frac{k}{2} \right \rceil$ to $k - 1$ inclusive. Notice that the sum of any two chosen numbers is already greater than $k$, and no chosen number is equal to $k$, therefore such set is correct. It contains $(n - k) + (k -\left \lceil \frac{k}{2} \right \rceil) = n - \left \lceil \frac{k}{2} \right \rceil$ numbers. Let's show why such size of a set is the maximal possible. Numbers from $k+1$ to $n$ won't give subsets with sum $k$ with any other numbers, so we can take them to the answer: their amount is $n - k$. The number $k$ can't be taken to the answer, because if we take a subset consisting from that number only, the sum in it will be $k$. Let's consider numbers from $1$ to $k-1$. They can be divided into $\left \lfloor \frac{k}{2} \right \rfloor$ pairs, in each of which the sum of numbers will be $k$ ($1$ and $k-1$, $2$ and $k-2$ etc.; if $k$ is even, then the pair with number $\frac{k}{2}$ will consist of one number). If we took at least $\left \lfloor \frac{k}{2} \right \rfloor + 1$ numbers from $1$ to $k-1$, then at least two chosen numbers will be in one pair, and their sum will be equal to $k$, what contradicts with problem condition. It means that we can take not more than $\left \lfloor \frac{k}{2} \right \rfloor$ numbers from $1$ to $k-1$. Then the total size of the set will not exceed $(n - k) + \left \lfloor \frac{k}{2} \right \rfloor$. As known, $k$ = $\left \lfloor \frac{k}{2} \right \rfloor + \left \lceil \frac{k}{2} \right \rceil$ (you can prove that fact by considering two cases: when $k$ is even, and when $k$ is odd). Let's replace $k$ in recieved estimation: $n - (\left \lfloor \frac{k}{2} \right \rfloor + \left \lceil \frac{k}{2} \right \rceil) + \left \lfloor \frac{k}{2} \right \rfloor=n - \left \lceil \frac{k}{2} \right \rceil$, which is the size of mentioned set, therefore mentioned set is the answer to the problem.
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t, n, k; cin >> t; while (t--) { cin >> n >> k; cout << n - k + k / 2 << '\n'; for (int i = k + 1; i <= n; ++i) cout << i << " "; for (int i = (k + 1) / 2; i < k; ++i) cout << i << " "; cout << '\n'; } return 0; }
1493
B
Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $h$ hours and each hour lasts $m$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $0$ to $h-1$ and minutes are numbered from $0$ to $m-1$. \begin{center} That's how the digits are displayed on the clock. Please note that digit $1$ is placed in the \textbf{middle} of its position. \end{center} A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. \begin{center} The reflection is not a valid time. The reflection is a valid time with $h=24$, $m = 60$. However, for example, if $h=10$, $m=60$, then the reflection is not a valid time. \end{center} An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $s$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any $h$, $m$, $s$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases.
In order to solve the problem, you need to look over all the moments of time after the given one and check if the reflected time is correct in that moment of time. If such moment of time does not exist on the current day, the moment $00:00$ of the next day is always correct. For realization you need to notice that digits $0$, $1$, $8$ transform into themselves after reflection, $2$ transforms into $5$, $5$ transforms into $2$, and other digits ($3$, $4$, $6$, $7$, $9$) transform into incorrect digits after reflection.
[ "brute force", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; vector < int > go = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1}; int inf = 1e9 + 7; int get(int x) { string s = to_string(x); if ((int)s.size() == 1) s = "0" + s; string answ = ""; for (int i = 1; i >= 0; --i) { if (go[s[i] - '0'] == -1) return inf; answ += char(go[s[i] - '0'] + '0'); } return stoi(answ); } string good(int x) { string ans = to_string(x); if (x < 10) { ans = "0" + ans; } return ans; } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t, h, m, H, M; cin >> t; string s; while (t--) { cin >> h >> m; cin >> s; H = (s[0] - '0') * 10 + s[1] - '0'; M = (s[3] - '0') * 10 + s[4] - '0'; while (1) { if (M == m) { H++, M = 0; } if (H == h) { H = 0; } if (get(M) < h && get(H) < m) { cout << good(H) << ":" << good(M) << '\n'; break; } M++; } } return 0; }
1493
C
K-beautiful Strings
You are given a string $s$ consisting of lowercase English letters and a number $k$. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by $k$. You are asked to find the lexicographically smallest beautiful string of length $n$, which is lexicographically greater or equal to string $s$. If such a string does not exist, output $-1$. 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$.
First of all, let's notice that if the length of the string $n$ is not divisible by $k$, no beautiful string of such length exists. Otherwise the answer to the problem always exists (because the string $zz \ldots z$ is the greatest string of length $n$ and is beautiful). If the string $s$ is beautiful, then $s$ itself is the answer. Otherwise, let's iterate over all the options of the maximal common prefix of the answer string and $s$, that way we will iterate from $n-1$ to $0$. Let's maintain an array $cnt_i$ - how many times does the $i$-th leter of English alphabet occur in the prefix we have fixed. We can recalculate that array totally in $0(n)$, because when we iterate to the smaller prefix we only need to change one value of $cnt$. Denote the length of common prefix as $pref$. Let's iterate over all possible letters at position $pref+1$ (numeration starts from one) in increasing order. We need to iterate over all letters that are strictly greater than $s_{pref+1}$, because otherwise either the answer will be less than $s$ or the length of common prefix won't be equal to $pref$. Now we need to learn how to check quickly if we can pick any suffix so that we will get a beautiful string. To do that you need to go through the array $cnt$ and to calculate for each letter which miminal number of times we need to write it more in order to get the amount of occurences divisible by $k$. For $i$-th leter it is $(k-cnt_i$ $\%$ $k)$ $\%$ $k$. Let $sum$ be the sum of such value over all $i$. If $sum$ isn't greater than the length of the suffix, then what's left is to find the minimal suffix. How to build the minimal suffix: let's denote the length of unknown suffix as $suff$ ($suff=n-pref-1$). We know that $sum \le suff$. If $sum < suff$, then let's increase the amount of occurences of $a$ on suffix by $suff-sum$. Now we will place all letters $a$, then all letters $b$ and so on to $z$. A detail of realization: we will consider iterated letter at position $pref+1$ in the array $cnt$. We can maintain array $cnt$ on prefix of length $pref+1$ and take into account that $pref+1$-st symbol is the iterated symbol and not the symbol of string $s$. The complexity of solution is $O(n \cdot C)$, where $C$ is the size of the alphabet ($26$). You can also write a solution in $O(n)$, by maintaining the sum $(k-cnt_i$ $\%$ $k)$ $\%$ $k$ in a variable.
[ "binary search", "brute force", "constructive algorithms", "greedy", "strings" ]
2,000
#include <bits/stdc++.h> using namespace std; int cnt[26]; int get(int x, int k) { return (k - x % k) % k; } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k, t; cin >> t; while (t--) { cin >> n >> k; string s; cin >> s; for (int j = 0; j < 26; ++j) cnt[j] = 0; for (auto c : s) cnt[c - 'a']++; int sum = 0, flag = 1; for (int i = 0; i < 26; ++i) { sum += get(cnt[i], k); } if (sum == 0) { cout << s << '\n'; flag = 0; } if (n % k != 0) { cout << -1 << '\n'; continue; } for (int i = n - 1; i >= 0 && flag; --i) { sum -= get(cnt[s[i] - 'a'], k); cnt[s[i] - 'a']--; sum += get(cnt[s[i] - 'a'], k); for (int j = s[i] - 'a' + 1; j < 26; ++j) { int lst_sum = sum; sum -= get(cnt[j], k); cnt[j]++; sum += get(cnt[j], k); if (i + sum + 1 <= n) { for (int pos = 0; pos < i; ++pos) { cout << s[pos]; } cout << char('a' + j); string add = ""; for (int w = 0; w < 26; ++w) { int f = get(cnt[w], k); while (f) { f--; add += char('a' + w); } } while ((int)add.size() + i + 1 < n) { add += "a"; } sort(add.begin(), add.end()); cout << add << '\n'; flag = 0; break; } cnt[j]--; sum = lst_sum; } } } return 0; }
1493
D
GCD of an Array
You are given an array $a$ of length $n$. You are asked to process $q$ queries of the following format: given integers $i$ and $x$, multiply $a_i$ by $x$. After processing each query you need to output the greatest common divisor (GCD) of all elements of the array $a$. Since the answer can be too large, you are asked to output it modulo $10^9+7$.
Notice that after each query the answer doesn't become smaller and we can solve the problem for each prime divisor independently. For each number let's maintain an amount of occurences for all its prime divisors (you can implement it using $map$). For each prime divisor let's write to its corresponding $multiset$ the amount of times it is met in every of the numbers of the array, at the same time we won't add null values. Initially, $ans=1$. Let's understand the way a prime divisor $p$ is included in the answer. If the size of its $multiset$ is not equal to $n$, then $ans$ won't change, otherwise $ans=(ans \cdot p^x)$ $\%$ $mod$, where $x$ is a minimal number of $multiset$. Since $ans$ is not decreasing, then we can avoid calculating it all over again every time and instead recalculate it only for divisors that are being changed (with that, because the minimal number of $multiset$ is not decreasing as well, we can just increase the answer using multiplication). To process the query, we need to find the prime factorization of $x$ (for example, using the Sieve of Eratosthenes) and add the prime divisors to the $map$ for $i$-th element (and correspondingly change the $multiset$ for that divisor). Each query is processed in the complexity of the amount of prime divisors multiplied by the time of $map$ and $multiset$ operation, i.e. $log$.
[ "brute force", "data structures", "hashing", "implementation", "math", "number theory", "sortings", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; int const maxn = 2e5 + 5, max_val = 2e5 + 5; ll mod = 1e9 + 7, ans = 1; int nxt[max_val], n; multiset <int> cnt[max_val]; map <int, int> cnt_divisor[maxn]; void add(int i, int x) { while (x != 1) { int div = nxt[x], add = 0; while (nxt[x] == div) add++, x = x / nxt[x]; int lst = cnt_divisor[i][div]; cnt_divisor[i][div] += add; int lst_min = 0; if ((int)cnt[div].size() == n) { lst_min = (*cnt[div].begin()); } if (lst != 0) { cnt[div].erase(cnt[div].find(lst)); } cnt[div].insert(lst + add); if ((int)cnt[div].size() == n) { for (int j = lst_min + 1; j <= (*cnt[div].begin()); ++j) { ans = ans * (ll)div % mod; } } } } main() { ios_base::sync_with_stdio(0); cin.tie(0); int q, l, x; cin >> n >> q; for (int i = 2; i < maxn; ++i) { if (nxt[i] == 0) { nxt[i] = i; if (i > 10000) continue; for (int j = i * i; j < maxn; j += i) { if (nxt[j] == 0) nxt[j] = i; } } } for (int i = 1; i <= n; ++i) { cin >> x; add(i, x); } for (int i = 1; i <= q; ++i) { cin >> l >> x; add(l, x); cout << ans << '\n'; } return 0; }
1493
E
Enormous XOR
You are given two integers $l$ and $r$ in binary representation. Let $g(x, y)$ be equal to the bitwise XOR of all integers from $x$ to $y$ inclusive (that is $x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y$). Let's define $f(l, r)$ as the maximum of all values of $g(x, y)$ satisfying $l \le x \le y \le r$. Output $f(l, r)$.
Let's numerate bits from $0$ to $n-1$ from the least significant bit to the most significant (from the end of the representation). If $n-1$-st bits of numbers $l$ and $r$ differ, then there is a power transition between numbers $l$ and $r$, and the answer to the problem is $11 \ldots 1$ (the number contains $n$ ones). Otherwise it can be shown that if $0$ bit of the number $r$ is equal to $1$, then the answer is $r$ itself. If $0$ bit of the number $r$ is equal to $0$ and $l <= r - 2$, the answer is $r+1$, otherwise the answer is $r$. Proof. Firstly, if there is a power transition between $l$ and $r$, then we can take a segment [$11 \ldots 1$; $100 \ldots 0$] ($n-1$ ones; $1$ and $n - 1$ zero), and get $\operatorname{xor}$ on it of $n$ ones. It is not hard to show that it will be the maximal possible. Let's prove that for odd $r$ without power transition the answer is $r$. That answer can be reached if we take a segment consisting of one number $r$. Let's prove that the answer if maximal using induction. Base: for segments $[r; r]$, $[r-1;r]$, $r$ is odd, the answer is $r$ (in the first case there is no other segments, in the second case subsegments $[r-1;r-1]$ and $[r-1;r]$ have less $\operatorname{xor}$-s). Let's take induction step from $[l;r]$ to $[l;r+2]$. The answer on segment $[r+1;r+2]$ is obviously $r+2$, remaining subsegments can be split into three groups: with right bound $r+2$, with right bound $r+1$, and lying inside the segment $[l; r]$, with that all the left bounds of the subsegments are lying inside $[l;r]$. The answer on the segments of third group is $r$ (proved by induction). The segments of the first group contain subsegment $[r+1;r+2]$, which has $\operatorname{xor}$ equal to $1$, and some segment ending at $r$. Notice that that way we can increase the answer of the segment $[l;r]$ not more by $1$, i.e. the answer for the segments of the first group is not greater than $r+1$. Now let's consider the segments of the second group. Suppose that we could find the segment from that group with $\operatorname{xor}$ on it greater than $r+2$. Then some bit which was $0$ in $r+2$, became $1$ in that $\operatorname{xor}$, with that it is not the $0$ bit (since $r+2$ is odd). Let's find the amount of numbers from $r+1$ (inclusively) to the nearest having $1$ in that bit (non-inclusively). It is not hard to show that that amount is odd (from even to zero inclusively). In order to make the bit $1$, we need to take an odd amount of numbers with $1$ in that bit. Since the blocks (among consecutive numbers blocks with $0$ in that bit and blocks with $1$ in that bit) have even length ($2$, $4$, $8$ and so on), we need to take an odd amount of numbers in total to take an odd amount of numbers with $1$ in that bit. Then the whole segment will contain odd $+$ odd $=$ even amount of numbers (the first summand is the amount of numbers from $r$ to the nearest having $1$ in that bit, the second summand is the amount of numbers we will take to make that bit equal to $1$), but then the most significant ($(n-1)$-st) bit will become equal to $0$, therefore we will get $\operatorname{xor}$ less than $r+2$. It means that among segments of the second group there is no segment with $\operatorname{xor}$ greater than $r+2$ as well. So, $r+2$ is the answer for $[l; r+2]$. Now let's consider even right bounds. If the length of the segment is less than $2$ ($l > r - 2$), then it is simple to show that the right bound will be the answer. Otherwise $r+1$ is the answer. It can be reached on the segment $[r-2;r]$ and is the maximal possible, because we can increase the right bound of the segment by $1$ (it will become odd), with that the answer surely won't decrease, and the answer on $[l;r+1]$ is proven to be $r+1$.
[ "bitmasks", "constructive algorithms", "greedy", "math", "strings", "two pointers" ]
2,600
#include<bits/stdc++.h> using namespace std; string add(string s) { int i = (int)s.size() - 1; while (s[i] == '1') { s[i] = '0'; i--; } s[i] = '1'; return s; } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; string l, r; cin >> l >> r; if (l == r) { cout << r << '\n'; return 0; } if (l[0] != r[0]) { for (int i = 1; i <= n; ++i) cout << "1"; return 0; } if (add(l) == r || r.back() == '1') { cout << r << '\n'; return 0; } cout << add(r) << '\n'; return 0; }
1493
F
Enchanted Matrix
This is an interactive problem. There exists a matrix $a$ of size $n \times m$ ($n$ rows and $m$ columns), you know only numbers $n$ and $m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, and columns of the matrix are numbered from $1$ to $m$ from left to right. The cell on the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$. You are asked to find the number of pairs $(r, c)$ ($1 \le r \le n$, $1 \le c \le m$, $r$ is a divisor of $n$, $c$ is a divisor of $m$) such that if we split the matrix into rectangles of size $r \times c$ (of height $r$ rows and of width $c$ columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal. You can use queries of the following type: - ? $h$ $w$ $i_1$ $j_1$ $i_2$ $j_2$ ($1 \le h \le n$, $1 \le w \le m$, $1 \le i_1, i_2 \le n$, $1 \le j_1, j_2 \le m$) — to check if \textbf{non-overlapping} subrectangles of height $h$ rows and of width $w$ columns of matrix $a$ are equal or not. The upper left corner of the first rectangle is $(i_1, j_1)$. The upper left corner of the second rectangle is $(i_2, j_2)$. Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect. You can use at most $ 3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor$ queries. All elements of the matrix $a$ are fixed before the start of your program and do not depend on your queries.
Te problem can be solved in various ways but the main idea is that if we want to check, if the $x$ consecutive blocks are equal to each other, then we can do it using $\left \lceil \log_2 x \right \rceil$ queries. Let's suppose we want to check the equality of $x$ blocks, then we will check if the first and second $\left \lfloor \frac {x} {2} \right \rfloor$ blocks are equal. If they are not equal, then $x$ blocks are not equal to each other, otherwise we need to check if the last $\left \lceil \frac {x} {2} \right \rceil$ blocks are equal. Notice that the problem can be solved independently for rows and columns. Let's solve the problem for $n$ rows and let's find all $r$ such that the matrix can be split into equal rectangles of $r$ rows. If $r$ is the answer, then the numbers that are divisible by $r$ are also the answers. If $r$ is not the answer, then all divisors of $r$ are not the answers. If $r1$ and $r2$ are the answers, then $\operatorname{gcd}(r1, r2)$ is the answer as well. Let's make a dynamic $dp_r$. If $dp_r = 1$, then the matrix can be divided into $r$ rows, otherwise $dp_r = 0$ and the matrix cannot be divided that way. We will iterate over $r$ in descending order. Let's suppose we want to calculate $dp_r$. Then we know for sure that for every $x$ that are divisors of $n$ and are divisible by $r$, $dp_x=1$ (because otherwise $dp_r=0$ and we don't have to calculate it). Let's find such minimal $x$ and check the equality of $\frac{x}{r}$ blocks using the idea described in the beginning of the editorial. Let's calculate the sum of $dp_r$ - that is the amount of suitable $r$. Then we will solve the problem similarly for columns and output the product of suitable $r$ and suitable $c$. It is guaranteed that with any initial field the described solution will ask less than $3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor$ queries. An accurate estimation of number of queries will be shown later. An accurate eastimation of number of queries: let us have the least $r$ such that we can split the matrix into $r$ rows (in order to get equal subrectangles) and all remaining $r$ are divided by it. Using that dynamic we maintain a minimal suitable $r$, and after that we try to decrease it using the algorithm from the editorial. The worst case is when we divide current minimal $r$ by $3$ with $2$ queries. Then we need $2 \cdot \log_3 n$ queries, which is equal to $\log_3 4 \cdot \log_2 n$.
[ "bitmasks", "interactive", "number theory" ]
2,600
#include <bits/stdc++.h> using namespace std; int const maxn = 1005; int dp[maxn]; vector < vector < int > > T; int ask(int lx1, int ly1, int rx1, int ry1, int lx2, int ly2, int rx2, int ry2) { cout << "? " << rx1 - lx1 + 1 << " " << ry1 - ly1 + 1 << " " << lx1 << " " << ly1 << " " << lx2 << " " << ly2 << endl; int ans; cin >> ans; return ans; } int good(int l, int r) { if (l == r) return 1; int cnt = (r - l + 1) / 2; if (ask(T[l][0], T[l][1], T[l + cnt - 1][2], T[l + cnt - 1][3], T[l + cnt][0], T[l + cnt][1], T[l + 2 * cnt - 1][2], T[l + 2 * cnt - 1][3])) { return good(l + cnt, r); } return 0; } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m, cntn = 0, cntm = 0; cin >> n >> m; for (int i = n; i >= 1; --i) { if (n % i != 0 || dp[i] != 0) continue; for (int j = 2 * i; j <= n; j += i) { if (n % j == 0 && j % i == 0) { T = {}; for (int k = 1; k <= j / i; ++k) { T.push_back({(k - 1) * i + 1, 1, k * i, m}); } if (good(0, (int)T.size() - 1)) dp[i] = 1; else dp[i] = 2; break; } } if (dp[i] == 2) { for (int j = 1; j <= n; ++j) { if (i % j == 0) dp[j] = 2; } } else { dp[i] = 1; for (int j = i; j <= n; ++j) { if (dp[j] == 1) { int w = __gcd(i, j); for (int pos = w; pos <= n; pos += w) { dp[pos] = 1; } } } } } for (int i = 1; i <= n; ++i) { if (n % i == 0) cntn += (dp[i] == 1); dp[i] = 0; } for (int i = m; i >= 1; --i) { if (m % i != 0 || dp[i] != 0) continue; for (int j = 2 * i; j <= m; j += i) { if (m % j == 0 && j % i == 0) { T = {}; for (int k = 1; k <= j / i; ++k) { T.push_back({1, (k - 1) * i + 1, n, k * i}); } if (good(0, (int)T.size() - 1)) dp[i] = 1; else dp[i] = 2; break; } } if (dp[i] == 2) { for (int j = 1; j <= i; ++j) { if (i % j == 0) { dp[j] = 2; } } } else { dp[i] = 1; for (int j = i; j <= m; ++j) { if (dp[j] == 1) { int w = __gcd(i, j); for (int pos = w; pos <= m; pos += w) { dp[pos] = 1; } } } } } for (int i = 1; i <= m; ++i) { if (m % i == 0) cntm += (dp[i] == 1); } cout << "! " << cntn * cntm << endl; return 0; }
1494
A
ABC String
You are given a string $a$, consisting of $n$ characters, $n$ is even. For each $i$ from $1$ to $n$ $a_i$ is one of 'A', 'B' or 'C'. A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. You want to find a string $b$ that consists of $n$ characters such that: - $b$ is a regular bracket sequence; - if for some $i$ and $j$ ($1 \le i, j \le n$) $a_i=a_j$, then $b_i=b_j$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket. Your task is to determine if such a string $b$ exists.
There are two key observations. First, a regular bracket sequence always starts with an opening bracket and ends with a closing one. Thus, the first letter of $a$ corresponds to an opening bracket and the last letter corresponds to a closing bracket. If they are the same, then the answer is "NO". Second, a regular bracket sequence has exactly $\frac n 2$ opening and $\frac n 2$ closing brackets. Thus, we can check if the counts of the remaining letter and the first letter of the string or the remaining letter and the last letter of the string make it $\frac n 2$ in total. If neither of them do, then the answer is "NO". If both do, then that means that there are $0$ occurrences of the remaining letter, so it doesn't matter what bracket it is assigned to. Finally, after the assignment is complete, check if the resulting string is a regular bracket sequence. For that you have to check if on any prefix the number of opening brackets is greater or equal to the number of closing brackets. And also if the total number of opening and closing brackets is the same. Overall complexity: $O(n)$ per testcase.
[ "bitmasks", "brute force", "implementation" ]
900
#include <bits/stdc++.h> using namespace std; bool solve() { string s; cin >> s; vector<int> d(3); int x = s[0] - 'A'; int y = s.back() - 'A'; if (x == y) return false; d[x] = 1; d[y] = -1; if (count(s.begin(), s.end(), 'A' + x) == s.length() / 2) d[3 ^ x ^ y] = -1; else d[3 ^ x ^ y] = 1; int bal = 0; for (char c : s) { bal += d[c - 'A']; if (bal < 0) return false; } return bal == 0; } int main() { int t; cin >> t; while (t--) { cout << (solve() ? "YES\n" : "NO\n"); } }
1494
B
Berland Crossword
Berland crossword is a puzzle that is solved on a square grid with $n$ rows and $n$ columns. Initially all the cells are white. To solve the puzzle one has to color some cells on the border of the grid black in such a way that: - exactly $U$ cells in the top row are black; - exactly $R$ cells in the rightmost column are black; - exactly $D$ cells in the bottom row are black; - exactly $L$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white. Your task is to check if there exists a solution to the given puzzle.
Consider some corner of the picture. If it's colored black, then it contributes to counts to both of the adjacent sides. Otherwise, it contributes to none. All the remaining cells can contribute only to the side they are on. There are $n-2$ of such cells on each side. So let's try all $2^4$ options of coloring the corners. After fixing the colors of the corners, we can calculate the number of cells that have to be colored on each side. That is calculated by taking the initial requirement and subtracting the adjacent colored corners from it. If any of the numbers is below $0$ or above $n-2$ then that corner coloring doesn't work. Otherwise, you can always color the cells in some way. Overall complexity: $O(1)$ per testcase.
[ "bitmasks", "brute force", "greedy", "implementation" ]
1,400
for _ in range(int(input())): n, U, R, D, L = map(int, input().split()) for mask in range(16): rU, rR, rD, rL = U, R, D, L if mask & 1: rU -= 1 rL -= 1 if mask & 2: rL -= 1 rD -= 1 if mask & 4: rD -= 1 rR -= 1 if mask & 8: rR -= 1 rU -= 1 if min(rU, rR, rD, rL) >= 0 and max(rU, rR, rD, rL) <= n - 2: print("YES") break else: print("NO")
1494
C
1D Sokoban
You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line. You start on a position $0$. There are $n$ boxes, the $i$-th box is on a position $a_i$. All positions of the boxes are distinct. There are also $m$ special positions, the $j$-th position is $b_j$. All the special positions are also distinct. In one move you can go one position to the left or to the right. If there is a box in the direction of your move, then you push the box to the next position in that direction. If the next position is taken by another box, then that box is also pushed to the next position, and so on. \textbf{You can't go through the boxes}. \textbf{You can't pull the boxes towards you}. You are allowed to perform any number of moves (possibly, zero). Your goal is to place as many boxes on special positions as possible. Note that some boxes can be initially placed on special positions.
Since you can only push boxes, you can't bring boxes from negative positions to positive ones and vice versa. Thus, negative boxes/special positions and positive boxes/special positions are two separate tasks. You can solve them independently with the same algorithm and add up the answers. So, we will only consider the positive boxes/special positions case. Notice that it never makes sense to move left. Thus, the only thing that determines the answer is the maximum position to the right you reach. For a naive algorithm, we could iterate over that position, push all boxes that we have encountered on our way ahead of us and calculate the number of boxes that are on special positions. That works in $O((n + m) \cdot MAXC)$, where $MAXC$ is maximum coordinate. To improve that solution we can notice that the positions that are the most optimal are actually the ones such that the first box is pushed to some special position. Consider the case the first box isn't on a special position, and there is a special position somewhere to the right of it. There are two types of boxes: the ones that are in the pile you would push if you move right and the remaining suffix. What happens if you move one step to the right? The number of boxes from the suffix on special positions doesn't change. The number of boxes from the pile on special positions doesn't decrease. This number changes depending on if there is a special position immediately to the right of the pile and underneath the first box. Since we considered the case where there is no special position underneath the first box, the number can't decrease. So we managed to improve the solution to $O((n + m) \cdot m)$. Still slow. Let's now learn to maintain the answer while moving the boxes. Precalculate $su_i$ - the number of boxes from the $i$-th to the last one that are already on special positions. That can be done with two pointers. Now iterate over the special position under the first box in the increasing order. Maintain the size of the pile and the number of special positions under the pile. The first value is just the index of the first box not in a pile. The second value is easier to obtain if you keep the index of the first special position after the pile (or $m$ if there are none). Also achievable with two pointers. The answer is the number of special positions under the pile plus the suffix answer for the boxes after the pile. Take the maximum of all options. The constraints are pretty free, so you could replace two pointers with binary searches if you wanted to. Overall complexity: $O(n + m)$ per testcase.
[ "binary search", "dp", "greedy", "implementation", "two pointers" ]
1,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int calc(const vector<int> &a, const vector<int> &b){ int n = a.size(); int m = b.size(); vector<int> su(n + 1); int r = m - 1; for (int i = n - 1; i >= 0; --i){ su[i] = su[i + 1]; while (r >= 0 && b[r] > a[i]) --r; if (r >= 0 && b[r] == a[i]) ++su[i]; } int ans = 0; int j = 0; r = 0; forn(l, m){ while (j < n && a[j] <= b[l] + j) ++j; while (r < m && b[r] - b[l] < j) ++r; ans = max(ans, r - l + su[j]); } return ans; } int main() { int t; scanf("%d", &t); forn(_, t){ int n, m; scanf("%d%d", &n, &m); vector<int> a(n), b(m); forn(i, n) scanf("%d", &a[i]); forn(i, m) scanf("%d", &b[i]); vector<int> al, bl, ar, br; forn(i, n){ if (a[i] < 0) al.push_back(-a[i]); else ar.push_back(a[i]); } forn(i, m){ if (b[i] < 0) bl.push_back(-b[i]); else br.push_back(b[i]); } reverse(al.begin(), al.end()); reverse(bl.begin(), bl.end()); printf("%d\n", calc(al, bl) + calc(ar, br)); } return 0; }
1494
D
Dogeforces
The Dogeforces company has $k$ employees. Each employee, except for lower-level employees, has at least $2$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates. The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.
We can solve the problem recursively from the root to the leaves. Let's maintain a list of leaf indices for the current subtree. If the list size is equal to $1$, then we can stop our recursion. Otherwise, we have to find the value of the root of the current subtree and split all leaves between child nodes. The root value is the maximum value of $a_{v,u}$ among all pairs $v, u$ belonging to a subtree (since the current root has at least $2$ child nodes, there is a pair of leaves for which the current root is the least common ancestor). If the value of the least common ancestor of the leaves $v$ and $u$ ($a_{v, u}$) is less than the value of the current root then $v$ and $u$ belong to the same child of the root. Using this fact, we can split all the leaves between the child nodes and then restore the subtrees for them recursively.
[ "constructive algorithms", "data structures", "dfs and similar", "divide and conquer", "dsu", "greedy", "sortings", "trees" ]
2,300
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) const int N = 505; int n; int a[N][N]; int c[2 * N]; vector<pair<int, int>> e; int calc(vector<int> ls) { if (sz(ls) == 1) return ls[0]; int res = -1; for (int u : ls) res = max(res, a[ls[0]][u]); vector<vector<int>> ch; ch.push_back({ls[0]}); for (int i = 1; i < sz(ls); ++i) { int v = ls[i]; int group = -1; for (int j = 0; j < sz(ch); ++j) { if (a[v][ch[j][0]] != res) { group = j; break; } } if (group == -1) { group = sz(ch); ch.push_back({}); } ch[group].push_back(v); } int v = n++; c[v] = res; for (int i = 0; i < sz(ch); ++i) { int u = calc(ch[i]); e.emplace_back(u, v); } return v; } int main() { cin >> n; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cin >> a[i][j]; for (int i = 0; i < n; ++i) c[i] = a[i][i]; vector<int> ls(n); iota(ls.begin(), ls.end(), 0); int root = calc(ls); cout << n << '\n'; for (int i = 0; i < n; ++i) cout << c[i] << ' '; cout << '\n' << root + 1 << '\n'; for (auto it : e) cout << it.first + 1 << ' ' << it.second + 1 << '\n'; }
1494
E
A-Z Graph
You are given a directed graph consisting of $n$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process $m$ queries with it. Each query is one of three types: - "$+$ $u$ $v$ $c$" — add arc from $u$ to $v$ with label $c$. It's guaranteed that there is no arc $(u, v)$ in the graph at this moment; - "$-$ $u$ $v$" — erase arc from $u$ to $v$. It's guaranteed that the graph contains arc $(u, v)$ at this moment; - "$?$ $k$" — find the sequence of $k$ vertices $v_1, v_2, \dots, v_k$ such that there exist both routes $v_1 \to v_2 \to \dots \to v_k$ and $v_k \to v_{k - 1} \to \dots \to v_1$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.
At first, if there should be both routes $v_1, v_2, \dots, v_k$ and $v_k, v_{k - 1}, \dots, v_1$ then there are both arcs $(v_1, v_2)$ and $(v_2, v_1)$, i. e. there should exist at least one pair $\{u, v\}$ that both arcs $(u, v)$ and $(v, u)$ are present in the graph. Now, if $k$ is odd, and we have at least one pair $\{u, v\}$ then we can simply create sequence $u, v, u, v, \dots, v, u$. This sequence is a palindrome so, obviously, both routes generate the same string. If $k$ is even (or $k = 2x$), we can note that in the sequence $v_1, v_2, \dots, v_{2x}$ there is a middle arc $(v_x, v_{x + 1})$ and it should have the same character as arc $(v_{x + 1}, v_x)$ (since it's a middle arc in reverse route $v_k, \dots, v_1$), i. e. there should exist at least one pair $\{u, v\}$ that both arcs $(u, v)$ and $(v, u)$ are present in the graph and have the same label. Now, if we have at least one such pair $\{u, v\}$ then routes $u, v, \dots, u, v$ and $v, u, \dots, v, u$ generate the same one-letter strings. Since each arc $(u, v)$ is a part of at most one pair $\{u, v\}$, we can just maintain two sets with pairs $\{u, v\}$: one for pairs with different labels and the other one for pairs with equal labels. If $k$ is odd, we check that at least one of the sets is not empty. If $k$ is even, we check that the second set is not empty.
[ "constructive algorithms", "data structures", "graphs", "hashing" ]
2,400
#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 pair<int, int> pt; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; map<pt, int> allEdges; set<pt> difPairs, eqPairs; fore (q, 0, m) { char tp; cin >> tp; if (tp == '+') { int u, v; char c; cin >> u >> v >> c; if (allEdges.count({v, u})) { if (allEdges[{v, u}] == c) eqPairs.emplace(min(u, v), max(u, v)); else difPairs.emplace(min(u, v), max(u, v)); } allEdges[{u, v}] = c; } else if (tp == '-') { int u, v; cin >> u >> v; if (eqPairs.count({min(u, v), max(u, v)})) eqPairs.erase({min(u, v), max(u, v)}); if (difPairs.count({min(u, v), max(u, v)})) difPairs.erase({min(u, v), max(u, v)}); allEdges.erase({u, v}); } else { int k; cin >> k; bool hasAns = !eqPairs.empty(); if (k & 1) hasAns |= !difPairs.empty(); cout << (hasAns ? "YES" : "NO") << '\n'; } } return 0; }
1494
F
Delete The Edges
You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. Your goal is to destroy all edges of the given graph. You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed. You can perform the \textbf{mode shift} operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the \textbf{mode shift}, the edges you go through are deleted in the following way: the first edge after the \textbf{mode shift} is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to. Can you destroy all the edges of the given graph?
Let's suppose our graph is split into two graphs $G_1$ and $G_2$, the first graph contains the edges we delete before the mode shift, the second graph contains the edges we delete after the mode shift. It's quite obvious that the graph $G_1$ has an eulerian path. The structure of $G_2$ is a bit harder to analyze, but we can prove that it is always a star graph (a vertex and some other vertices connected directly to it), and the center of the star coincides with the last vertex in the eulerian path in $G_1$. To prove that $G_2$ is a star graph, we can consider the second part of the path (after the mode shift) backward: the last edge we traversed was deleted, and the previous-to-last move could have been only along that edge. The third-last and the fourth-last moves should have been along another edge connecting some vertex to the center of the star, and so on. Okay, how do we find a way to split the graph into $G_1$ and $G_2$? Iterate on the center of the star (let it be $c$). For the graph $G_1$ to contain an eulerian path, it should have at most $2$ vertices with an odd degree. Let's construct $G_2$ in such a way that we minimize the number of odd vertices in $G_1$ - for each edge incident to $c$, we either move it to $G_1$ or $G_2$ in such a way that the resulting degree of the other vertex is even. All other edges belong to $G_1$. If there is an eulerian path in $G_1$ that ends in $c$, we are done. Otherwise, we should iterate on some edge adjacent to $c$ and change its status (in order to check if $G_1$ can have an eulerian path after that). We can't "flip" two edges because flipping two edges increases the number of odd vertices in $G_1$ at least by $2$ (if it is already $2$ or greater, the eulerian path won't exist, and if it's $0$, then flipping two edges creates two odd vertices, none of which is $c$, so eulerian path can't end in $c$). After flipping each edge, we try to find an eulerian path in $G_1$ once again and flip the edge back. After checking the vertex $c$ as the center of the star, we return all adjacent edges to $G_1$ and move to the next vertex. The whole algorithm requires checking for the existence of the eulerian path $O(n + m)$ times, so it should work in $O((n+m)^2)$ or $O((n+m)^2 \log n)$ depending on the implementation. Fun fact: initially I wanted to give a harder version of a problem with $n, m \le 2 \cdot 10^5$ that would require some sort of dynamic connectivity to check for an eulerian path fast, but when I started coding it, I realized that implementation there was a bit painful, so I've decided to drop the constraints to allow quadratic solutions.
[ "brute force", "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
2,900
#include <bits/stdc++.h> using namespace std; const int N = 300043; int n, m; set<int> g[N]; set<int> g2[N]; vector<int> res; void euler(int x) { while(!g2[x].empty()) { int y = *g2[x].begin(); g2[x].erase(y); g2[y].erase(x); euler(y); } res.push_back(x); } bool check(int c) { for(int i = 1; i <= n; i++) g2[i] = g[i]; res = vector<int>(); euler(c); int curm = 0; for(int i = 1; i <= n; i++) curm += g[i].size(); for(int i = 1; i <= n; i++) g2[i] = g[i]; for(int i = 1; i < res.size(); i++) { int x = res[i - 1]; int y = res[i]; if(g2[x].count(y) != 1) return false; g2[x].erase(y); g2[y].erase(x); } return curm / 2 + 1 == res.size(); } int main() { scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int x, y; scanf("%d %d", &x, &y); g[x].insert(y); g[y].insert(x); } for(int i = 1; i <= n; i++) { set<int> pr = g[i]; set<int> diff; for(auto x : pr) if(g[x].size() % 2 == 1) { g[i].erase(x); g[x].erase(i); diff.insert(x); } if(check(i)) { res.push_back(-1); for(auto x : diff) { res.push_back(x); res.push_back(i); } printf("%d\n", res.size()); for(auto x : res) printf("%d ", x); puts(""); exit(0); } for(auto x : pr) { if(g[i].count(x)) { g[i].erase(x); g[x].erase(i); diff.insert(x); } else { g[i].insert(x); g[x].insert(i); diff.erase(x); } if(check(i)) { res.push_back(-1); for(auto x : diff) { res.push_back(x); res.push_back(i); } printf("%d\n", res.size()); for(auto x : res) printf("%d ", x); puts(""); exit(0); } if(g[i].count(x)) { g[i].erase(x); g[x].erase(i); diff.insert(x); } else { g[i].insert(x); g[x].insert(i); diff.erase(x); } } for(auto x : diff) { g[i].insert(x); g[x].insert(i); } } puts("0"); }
1495
A
Diamond Miner
Diamond Miner is a game that is similar to Gold Miner, but there are $n$ miners instead of $1$ in this game. The mining area can be described as a plane. The $n$ miners can be regarded as $n$ points \textbf{on the y-axis}. There are $n$ diamond mines in the mining area. We can regard them as $n$ points \textbf{on the x-axis}. For some reason, \textbf{no miners or diamond mines can be at the origin} (point $(0, 0)$). Every miner should mine \textbf{exactly} one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $(a,b)$ uses his hook to mine a diamond mine at the point $(c,d)$, he will spend $\sqrt{(a-c)^2+(b-d)^2}$ energy to mine it (the distance between these points). The miners can't move or help each other. The object of this game is to minimize \textbf{the sum of the energy} that miners spend. Can you find this minimum?
First, you can turn a point $(x,y)$ to $(|x|,|y|)$, while not changing the answer. After this operation, all points can be described as $(0,a)$ or $(b,0)$ ($a,b > 0$). In a triangle, if the length of the edges are $a$, $b$, $c$, it is obvious that $a+b > c$. So, if you connect all match-pairs with a segment and there are two segments intersecting each other, you must be able to change the matching ways to make the answer smaller. For example, if you match $A(a_1,0)$ with $B(0,b_1)$, $C(a_2,0)$ with $D(0,b_2)$, the answer will be $|AB|+|CD|$; if you match $A$ with $D$ and $B$ with $C$, the answer will be $|AD|+|BC| < |AO|+|DO|+|BO|+|CO| = |AB|+|CD|$. So in the best solution, there won't be two segments intersecting each other. Sort all the points on the x-axis and on the y-axis, then match the points in ascending order of $x$ or $y$, you can get the minimum. The time complexity is $O(n \log n)$ for each test case.
[ "geometry", "greedy", "math", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; int n,X[maxn],Y[maxn],t1,t2; int main(){ int T; scanf("%d",&T); for(int i(1);i <= T;++i){ scanf("%d",&n); t1 = t2 = 0; for(int i(1);i <= 2*n;++i){ int x,y; scanf("%d%d",&x,&y); if(x == 0) Y[++t2] = abs(y); else X[++t1] = abs(x); } sort(X+1,X+1+t1); sort(Y+1,Y+1+t2); double Ans = 0; for(int i(1);i <= n;++i) Ans += sqrt(1.0*X[i]*X[i]+1.0*Y[i]*Y[i]); printf("%.15lf\n",Ans); } return 0; }
1495
B
Let's Go Hiking
On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper. A permutation $p$ is written from left to right on the paper. First Qingshan chooses an integer index $x$ ($1\le x\le n$) and tells it to Daniel. After that, Daniel chooses another integer index $y$ ($1\le y\le n$, $y \ne x$). The game progresses turn by turn and as usual, Qingshan moves first. The rules follow: - If it is Qingshan's turn, Qingshan must change $x$ to such an index $x'$ that $1\le x'\le n$, $|x'-x|=1$, $x'\ne y$, and $p_{x'}<p_x$ at the same time. - If it is Daniel's turn, Daniel must change $y$ to such an index $y'$ that $1\le y'\le n$, $|y'-y|=1$, $y'\ne x$, and $p_{y'}>p_y$ at the same time. The person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible $x$ to make Qingshan win in the case both players play optimally.
Let's consider that the $2k+1(k\ge 0)$-th turn is Qingshan's and the $2k+2(k\ge 0)$-th turn is Daniel's. If Qingshan chooses $x(1<x\le n)$ satisfying $x=n$ or $p_x<p_{x+1}$, then Daniel can choose $y=x-1$ to make Qingshan can't move in the first turn. The case that $x=1$ or $p_x<p_{x-1}$ is the same. So Qingshan must choose $x(1<x<n)$ satisfying $p_x>p_{x-1}$ and $p_x>p_{x+1}$ at first. Let $l$ be the length of the longest monotone segments and $c$ be the number of the longest monotone segments. $l\ge 2$ and $c\ge 1$ are always true. It is obvious that Qingshan can't win when $c>2$ because wherever Qingshan chooses, Daniel can always find a place that he can move $l-1$ times while Qingshan can move $l-1$ times at most. When $c=1$, Qingshan will also lose. If the only longest monotone segment is $p_s,p_{s+1}\dots,p_{s+l-1}$ and it's increasing(if it's decreasing, the discussion is almost the same). Qingshan must choose $x=s+l-1$ at first. The discussion follows: If $l\bmod 2=0$, Daniel can choose $y=s$ at first. After the $l-3$-th turn(Qingshan's turn), $x=s+l-\frac{l}{2}$ and After the $l-2$-th turn(Daniel's turn), $y=s+\frac{l}{2}-1$. The next turn is Qingshan's and Qingshan loses. If $l\bmod 2=1$, Daniel can choose $y=s+1$ at first. Pay attention that Qingshan can't change $x$ to $x+1$ in the first turn because Daniel can move $l-2$ times while Qingshan can move $l-2$ times at most if she change $x$ to $x+1$ in the first turn. After the $l-4$-th turn(Qingshan's turn), $x=s+l-\frac{l-1}{2}$ and After the $l-3$-th turn(Daniel's turn), $y=s+\frac{l-1}{2}$. The next turn is Qingshan's and Qingshan loses. When $c=2$ , the only two longest monotone segments must be like $p_{m-l+1}<p_{m-l+2}<\cdots<p_m>p_{m+1}>\cdots>p_{m+l-1}$. (Otherwise Qingshan will lose.) In that case Qingshan will lose if $l\bmod 2=0$ because Daniel can choose $y=m-l+1$ at first and whatever Qingshan's first move is, Qingshan will lose(just like the discussion above). If $l\bmod 2=1$, Qingshan is the winner. It is not hard to check it in $O(n)$. The overall time complexity is $O(n)$.
[ "games", "greedy" ]
1,900
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } template<typename T>void write(T x){ static char q[65];int cnt=0; if(x<0)pc('-'),x=-x; q[++cnt]=x%10,x/=10; while(x) q[++cnt]=x%10,x/=10; while(cnt)pc(q[cnt--]+'0'); } const int maxn=100005; int p[maxn],d[maxn]; int main(){ int n;read(n); for(int i=1;i<=n;++i)read(p[i]); for(int i=2;i<=n;++i)d[i]=(p[i-1]<p[i]); int MX=0,CNT=0; for(int l=2,r=2;l<=n;l=r=r+1){ int o=d[l]; while(r+1<=n&&o==d[r+1])++r; int len=r-l+2; if(len>MX)MX=len,CNT=1; else if(len==MX)++CNT; } if(CNT!=2||(MX&1)==0)return puts("0"),0; int ok=false; for(int i=3;i<=n&&!ok;++i){ if(d[i-1]&&!d[i]){ int l=i-1,r=i; while(l>2&&d[l-1])--l; while(r<n&&!d[r+1])++r; if((i-1)-(l-1)+1==MX&&r-(i-1)+1==MX) ok=true; } } write(ok),pc('\n'); return 0; }
1495
C
Garden of the Sun
There are many sunflowers in the Garden of the Sun. Garden of the Sun is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, \textbf{any two empty cells have no common points} (neither edges nor corners). Now the owner wants to remove some (possibly zero) sunflowers to reach the following two goals: - When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected. - There is \textbf{exactly one} simple path between any two empty cells. In other words, there is no cycle among the empty cells. You can walk from an empty cell to another if they share a common edge. Could you please give the owner a solution that meets all her requirements? Note that you are not allowed to plant sunflowers. You \textbf{don't need} to minimize the number of sunflowers you remove. It can be shown that the answer always exists.
When $m$ is the multiple of $3$, it's easy to construct a solution: First, remove all the sunflowers on column $2,5,8,11,\ldots$. This operation won't form a cycle in the graph. Let's take this as an example: After the operation, the graph turns into: After that, you need to connect these columns to make them connected but without forming a cycle. The green cells are all alternatives. This way of construction also works for $m=3k+2$. But you need to be cautious about the case of $m=3k+1$ because there is an extra column that may not be connected with the left part. Don't forget to connect them. Another approach is to remove column $1,4,7,10,\ldots$ when $m=3k+1$. So there won't be an extra column. The time complexity is $O(nm)$ for each test case.
[ "constructive algorithms", "graphs" ]
2,300
#include <bits/stdc++.h> const int MX = 1e3 + 23; int read(){ char k = getchar(); int x = 0; while(k < '0' || k > '9') k = getchar(); while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar(); return x; } char str[MX][MX]; void solve(){ int n = read() ,m = read(); for(int i = 1 ; i <= n ; ++i){ scanf("%s" ,str[i] + 1); } for(int i = 1 + (m % 3 == 0) ; i <= m ; ){ for(int j = 1 ; j <= n ; ++j) str[j][i] = 'X'; i += 3; if(i > m) break; int p = 1; if(n == 1 || (str[2][i - 1] != 'X' && str[2][i - 2] != 'X')) p = 1; else p = 2; str[p][i - 1] = str[p][i - 2] = 'X'; } for(int i = 1 ; i <= n ; ++i) puts(str[i] + 1); } int main(){ int T = read(); for(int i = 1 ; i <= T ; ++i) solve(); return 0; }
1495
D
BFS Trees
We define a spanning tree of a graph to be a BFS tree rooted at vertex $s$ if and only if for every node $t$ the shortest distance between $s$ and $t$ in the graph is equal to the shortest distance between $s$ and $t$ in the spanning tree. Given a graph, we define $f(x,y)$ to be the number of spanning trees of that graph that are BFS trees rooted at vertices $x$ and $y$ at the same time. You are given an undirected connected graph with $n$ vertices and $m$ edges. Calculate $f(i,j)$ for all $i$, $j$ by modulo $998\,244\,353$.
Let's enumerate vertexes $x,y$, and calculate $f(x,y)$ for them. Let $dist(x,y)$ denote the number of the vertexes which lie on the shortest-path between $x$ and $y$ on the graph. It is obvious that the distance between $x$ and $y$ in the tree is equal to $dist(x,y)$. And the vertex $z$ satisfying $dist(x,z)+dist(y,z)-1=dist(x,y)$ must be on the path between $x$ and $y$. So the number of the vertexes $z$ must be equal to $dist(x,y)$ ( including $x$ and $y$ ). Then, let's consider the contributions of other vertexes $i$. In the bfs-trees of both $x$ and $y$, there must be and only be a edge linking $i$ and $j$, which $j$ satisfies $dist(x,i)=dist(x,j)+1\land dist(y,i)=dist(y,j)+1$. Proof : Let's prove it recursively. All the vertexes linked to the path between $x$ and $y$ satisfy the condition ( There is and only is a edge linking them ). We can call them layer 1. All the vertexes linked to the layer 1 satisfy the condition ( There is and only is a edge linking them ). We can call them layer 2. All the vertexes ... End of proof And the contribution of each vertex is independent, which means that for each vertex $i$ we can choose a vertex $j$ without considering other vertexes. Proof : No matter which $j$ we choose for $i$, the layer of $i$ will not change. So the choice of $i$ won't change the number of choices of others. End of proof So we only need calculate the number of $j$ for every $i$, and multiply them. For every $x,y$, we should enumerate all the edges to calculate $j$ for every $i$. So the complexity is $O(m)$ per $x,y$. The total complexity is $O(n^2m)$.
[ "combinatorics", "dfs and similar", "graphs", "math", "shortest paths", "trees" ]
2,600
#pragma GCC optimize(2) #include <bits/stdc++.h> #define debug(...) fprintf(stderr, __VA_ARGS__) #define RI register int typedef long long LL; #define FILEIO(name) freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); using namespace std; namespace IO { char buf[1000000], *p1 = buf, *p2 = buf; inline char gc() { if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin); return p1 == p2 ? EOF : *(p1++); } template <class T> inline void read(T &n) { n = 0; RI ch = gc(), f; while ((ch < '0' || ch > '9') && ch != '-') ch = gc(); f = (ch == '-' ? ch = gc(), -1 : 1); while (ch >= '0' && ch <= '9') n = n * 10 + (ch ^ 48), ch = gc(); n *= f; } char Of[105], *O1 = Of, *O2 = Of; template <class T> inline void print(T n, char ch = '\n') { if (n < 0) putchar('-'), n = -n; if (n == 0) putchar('0'); while (n) *(O1++) = (n % 10) ^ 48, n /= 10; while (O1 != O2) putchar(*(--O1)); putchar(ch); } } using IO :: read; using IO :: print; int const mod = 998244353; int const MAXN = 505; struct Edges { int to, next; } e[MAXN << 2]; int head[MAXN], tot; int dis[MAXN][MAXN]; queue <int> q; int n, m; int Ans[MAXN][MAXN]; inline void addedge(int from, int to) { e[++tot] = (Edges){to, head[from]}; head[from] = tot; e[++tot] = (Edges){from, head[to]}; head[to] = tot; } void Getdis(int S, int *dis) { for (RI i = 1; i <= n; ++i) dis[i] = 0; q.push(S); dis[S] = 1; while (!q.empty()) { int t = q.front(); q.pop(); for (RI i = head[t]; i; i = e[i].next) if (!dis[e[i].to]) dis[e[i].to] = dis[t] + 1, q.push(e[i].to); } } int main() { #ifdef LOCAL FILEIO("a"); #endif read(n), read(m); for (RI i = 1, x, y; i <= m; ++i) read(x), read(y), addedge(x, y); for (RI i = 1; i <= n; ++i) Getdis(i, dis[i]); for (RI x = 1; x <= n; ++x) for (RI y = x; y <= n; ++y) { int cnt = 0; for (RI i = 1; i <= n; ++i) if (dis[x][i] + dis[y][i] - 1 == dis[x][y]) ++cnt; LL ans = 1; if (cnt > dis[x][y]) ans = 0; for (RI i = 1; i <= n; ++i) if (dis[x][i] + dis[y][i] - 1 != dis[x][y]) { int flag = 0; for (RI j = head[i]; j; j = e[j].next) if (dis[x][e[j].to] == dis[x][i] - 1 && dis[y][e[j].to] == dis[y][i] - 1) ++flag; ans = ans * flag % mod; if (!ans) break; } Ans[x][y] = Ans[y][x] = ans; } for (RI i = 1; i <= n; ++i) for (RI j = 1; j <= n; ++j) printf("%d%c", Ans[i][j], " \n"[j == n]); return 0; } // created by Daniel yuan /* ________ / \ / / \ \ / / \ \ \ / \ ______ / \________/ */
1495
E
Qingshan and Daniel
Qingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make $n$ robots in total to play this game automatically. Robots made by Qingshan belong to the team $1$, and robots made by Daniel belong to the team $2$. Robot $i$ belongs to team $t_i$. Before the game starts, $a_i$ cards are given for robot $i$. The rules for this card game are simple: - Before the start, the robots are arranged in a circle in the order or their indices. The robots will discard cards in some order, in each step one robot discards a single card. When the game starts, robot $1$ will discard one of its cards. After that, robots will follow the following rules: - If robot $i$ discards the card last, the nearest robot whose team is opposite from $i$'s will discard the card next. In another word $j$ will discard a card right after $i$, if and only if among all $j$ that satisfy $t_i\ne t_j$, $dist(i,j)$ (definition is below) is minimum. - The robot who has no cards should quit the game immediately. This robot won't be considered in the next steps. - When no robot can discard the card next, the game ends. We define the distance from robot $x$ to robot $y$ as $dist(x,y)=(y-x+n)\bmod n$. It is similar to the oriented distance on the circle. For example, when $n=5$, the distance from $1$ to $3$ is $dist(1,3)=(3-1+5)\bmod 5=2$, the distance from $3$ to $1$ is $dist(3,1)=(1-3+5)\bmod 5 =3$. Later, Qingshan finds out that it will take so much time to see how robots play. She wants to know the result as quickly as possible. You, as Qingshan's fan, are asked to calculate an array $[ans_1,ans_2,\ldots,ans_n]$ — $ans_i$ is equal to the number of cards, that $i$-th robot will discard during the game. You need to hurry! To avoid the large size of the input, the team and the number of cards of each robot will be generated in your code with some auxiliary arrays.
We can consider that the robots are standing on a cycle. The game ends up with at least one team having no cards. Let the team having no cards in the end be team $A$ and let the other be team $B$. If two teams both use up their cards, the first robot's team is $A$. For team $A$, we've already known how many cards will its robots discard, because they will discard all their cards. But how to calculate the answer for team $B$? Let's look at the process of the game. Obviously, robots in $A$ and robots in $B$ will discard cards alternatively. In another word, if we write down the team of robots who discard cards in time order, it will form a sequence - $ABABAB\cdots B$ or $BABABA\cdots B$. For the second type (starting with $B$), we can just use brute-force to discard the first card and then find the next $A$. So there is only one circumstance: $ABABAB\cdots B$. Note that in the sequence every $A$ is followed by exactly one $B$. So the length of the sequence is the number of cards of team $A$ multiplying $2$. Currently, we are not able to figure out which robot is exactly represented by a particular $A$ or $B$ in the sequence. Luckily, we don't need to know it. What we care about is only how many cards the robot in team $B$ discards. You can consider every $AB$ is the sequence as a query and change operation - "In the current game, some robot $i$ in team $A$ will find the first robot $j$ in team $B$ on its right, and change $a_j$ to $a_j-1$". It's a very important limit "In the current game" here because some robot will quit the game halfway according to the statement. But on the contrary, an interesting fact is that the "important" limit is not important at all. We can make the query and the change in any order and it won't change the answer! So you just need to iterate the array and maintain a variable $cnt$ - the number of operations that are visited but not performed. If the team of the current robot is $A$, assign $cnt+a_i$ to $cnt$. Otherwise, you can perform $\min(a_i, cnt)$ operations now, and assign $a_i-\min(a_i,cnt)$ to $a_i$. Since robots are standing on a cycle, you need to iterate the array $2$ times. So the time complexity is $O(n+m)$.
[ "brute force", "data structures", "greedy", "implementation" ]
3,200
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define __FILE(x)\ freopen(#x".in" ,"r" ,stdin);\ freopen(#x".out" ,"w" ,stdout) #define LL long long const int MX = 5e6 + 23; const LL MOD = 1e9 + 7; int read(){ char k = getchar(); int x = 0; while(k < '0' || k > '9') k = getchar(); while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar(); return x; } int a[MX] ,team[MX] ,org[MX]; int n ,m; LL s[2]; int seed ,base; int rnd(){ int ret = seed; seed = (1LL * seed * base + 233) % MOD; return ret; } int main(){ n = read() ,m = read(); int lastp = 0; for(int i = 1 ,p ,k ,b ,w ; i <= m ; ++i){ p = read() ,k = read() ,b = read() ,w = read(); seed = b ,base = w; for(int j = lastp ; j < p ; ++j){ team[j] = rnd() % 2; s[team[j]] += (org[j] = a[j] = rnd() % k + 1); // printf("team %d a[%d] = %d\n" ,team[j] ,j ,a[j]); } lastp = p; } int st = 0; if(s[team[0]] > s[!team[0]]){ s[team[0]]-- ,a[0]--; while(team[0] == team[st] && st < n) ++st; } int cur = st; LL sum = 0; if(st != n) while(s[team[st]]){ if(team[cur] == team[st]){ sum += a[cur]; a[cur] = 0; } else{ LL d = std::min(1LL * a[cur] ,sum); s[team[st]] -= d; sum -= d; a[cur] -= d; } cur = (cur + 1 == n ? 0 : cur + 1); } LL ans = 1; for(int i = 0 ; i < n ; ++i){ LL qwq = (((org[i] - a[i]) ^ (1LL * (i + 1) * (i + 1))) + 1) % MOD; ans = ans * qwq % MOD; } printf("%lld\n" ,ans); // for(int i = 0 ; i < n ; ++i) printf("%d%c" ,org[i] - a[i] ," \n"[i == n - 1]); return 0; }
1495
F
Squares
There are $n$ squares drawn from left to right on the floor. The $i$-th square has three integers $p_i,a_i,b_i$, written on it. The sequence $p_1,p_2,\dots,p_n$ forms a permutation. Each round you will start from the leftmost square $1$ and jump to the right. If you are now on the $i$-th square, you can do one of the following two operations: - Jump to the $i+1$-th square and pay the cost $a_i$. If $i=n$, then you can end the round and pay the cost $a_i$. - Jump to the $j$-th square and pay the cost $b_i$, where $j$ is the leftmost square that satisfies $j > i, p_j > p_i$. If there is no such $j$ then you can end the round and pay the cost $b_i$. There are $q$ rounds in the game. To make the game more difficult, you need to maintain a square set $S$ (initially it is empty). You \textbf{must} pass through these squares during the round (other squares can also be passed through). The square set $S$ for the $i$-th round is obtained by adding or removing a square from the square set for the $(i-1)$-th round. For each round find the minimum cost you should pay to end it.
If we let the parent of $i(1\le i\le n)$ is the rightmost $j$ satisfying $j<i,p_j>p_i$(if that $j$ doesn't exist, the parent of $i$ is $0$), we can get a tree and we can dfs the tree with the order $0,1,2,\dots,n$. Let's call the parent of $i$ is $\operatorname{pa}_i$ and the children set of $i$ is $\operatorname{child}_i$. Here is an example. $n=5$ and the permutation is $2,1,5,3,4$. The graphs we build follow. Let's call the edges with the cost $a_i$ A-type and the edges with the cost $b_i$ B-type. Consider that now you are on the $i$-th square. If you choose a B-type edge(with the cost $b_i$), you will jump over all the squares in $i$'s subtree($i$ is not included), that is to say, you will not pass through them. If you choose an A-type edge, we can think you enter $i$'s subtree and you must pass through all of the $i$'s child. To simplify the problem, we think you choose a node $i$ if and only if you pass through the A-type edge from the $i$-th square. Let's call the chosen set is $S$. It is not hard to find out that the node $i$ can be chosen if and only if all the ancestors of $i$ in the tree are chosen(if not, you even don't have the chance to pass through $i$). And that you pass through the $i$-th square is equivalent to you choosing the parent of $i$. Then the problem is simplified. You purpose is to choose some nodes in the tree ($0$ must be chosen as it is the root) and minimize your cost. Here your cost is $\sum_{i\in S}a_i+\sum_{i\not\in S,\operatorname{pa}_i\in S}b_i$. If we let $c_i=a_i-b_i+\sum_{j\in\operatorname{child}_i}b_j$, the cost can be considered as $\sum_{i\in S}c_i+\sum_{j\in\operatorname{child}_0}b_j$. It is very easy to solve it with binups. The time complexity is $O((n+q)\log n)$.
[ "constructive algorithms", "data structures", "dp", "graphs", "trees" ]
3,300
#include<set> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } template<typename T>void write(T x){ static char q[65];int cnt=0; if(x<0)pc('-'),x=-x; q[++cnt]=x%10,x/=10; while(x) q[++cnt]=x%10,x/=10; while(cnt)pc(q[cnt--]+'0'); } const int maxn=200005; int p[maxn],st[maxn],tp,pa[maxn][22],dp[maxn]; long long a[maxn],b[maxn],val[maxn],dis[maxn]; int lca(int x,int y){ if(dp[x]<dp[y])x^=y^=x^=y; for(int t=dp[x]-dp[y],cn=0;t;t>>=1,++cn) if(t&1)x=pa[x][cn]; if(x==y)return x; for(int t=20;t>=0;--t) if(pa[x][t]!=pa[y][t]) x=pa[x][t],y=pa[y][t]; return pa[x][0]; } int vis[maxn],cnt[maxn];set<int>s; long long sum; long long dist(int x,int y){ return dis[x]+dis[y]-2*dis[lca(x,y)]; } set<int>::iterator it; void ins(int x){ it=s.insert(x).first;int l=*(--it);++it;++it; int r=((it==s.end())?*s.begin():*it); sum+=dist(l,x)+dist(x,r)-dist(l,r); } void del(int x){ it=s.find(x);int l=*(--it);++it;++it; int r=((it==s.end())?*s.begin():*it); sum-=dist(l,x)+dist(x,r)-dist(l,r); --it;s.erase(it); } int main(){ int n,q;read(n),read(q); for(int i=1;i<=n;++i){ read(p[i]); while(tp&&p[st[tp]]<p[i])--tp; dp[i]=dp[pa[i][0]=st[tp]]+1;st[++tp]=i; for(int j=1;(1<<j)<=dp[i];++j) pa[i][j]=pa[pa[i][j-1]][j-1]; } for(int i=1;i<=n;++i)read(a[i]),val[i]+=a[i]; for(int i=1;i<=n;++i)read(b[i]),val[i]-=b[i],val[pa[i][0]]+=b[i]; for(int i=n;i>=1;--i)dis[pa[i][0]]+=min(0ll,dis[i]+=val[i]),dis[i]-=min(0ll,dis[i]); dis[0]+=val[0];for(int i=1;i<=n;++i)dis[i]+=dis[pa[i][0]];cnt[0]=1;s.insert(0); while(q--){ int x;read(x); if(vis[x]){ vis[x]=false; if(!(--cnt[pa[x][0]])) del(pa[x][0]); } else{ vis[x]=true; if(!(cnt[pa[x][0]]++)) ins(pa[x][0]); } write(sum/2+dis[0]),pc('\n'); } return 0; }
1496
A
Split it!
Kawashiro Nitori is a girl who loves competitive programming. One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem. Given a string $s$ and a parameter $k$, you need to check if there exist $k+1$ non-empty strings $a_1,a_2...,a_{k+1}$, such that $$s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}).$$ Here $+$ represents concatenation. We define $R(x)$ as a reversed string $x$. For example $R(abcd) = dcba$. Note that in the formula above the part $R(a_{k+1})$ is intentionally skipped.
If $k=0$ or $s[1,k]+s[n-k+1,n]$ is a palindrome, the answer is yes. Otherwise, the answer is no. Note that when $2k=n$, the answer is no, too. The time complexity is $O(n+k)$ for each test case.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
900
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define __FILE(x)\ freopen(#x".in" ,"r" ,stdin);\ freopen(#x".out" ,"w" ,stdout) #define LL long long const int MX = 100 + 23; const LL MOD = 998244353; int read(){ char k = getchar(); int x = 0; while(k < '0' || k > '9') k = getchar(); while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar(); return x; } char s[MX]; void solve(){ int n = read() ,k = read(); scanf("%s" ,s); int ok = 1; for(int i = 0 ; i < k ; ++i) ok = ok && s[i] == s[n - i - 1]; puts(ok && k * 2 < n ? "YES" : "NO"); } int main(){ int T = read(); for(int i = 1 ; i <= T ; ++i){ solve(); } return 0; }
1496
B
Max and Mex
You are given a multiset $S$ initially consisting of $n$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times. You will perform the following operation $k$ times: - Add the element $\lceil\frac{a+b}{2}\rceil$ (rounded up) into $S$, where $a = \operatorname{mex}(S)$ and $b = \max(S)$. If this number is already in the set, it is added again. Here $\operatorname{max}$ of a multiset denotes the maximum integer in the multiset, and $\operatorname{mex}$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example: - $\operatorname{mex}(\{1,4,0,2\})=3$; - $\operatorname{mex}(\{2,5,1\})=0$. Your task is to calculate the number of \textbf{distinct} elements in $S$ after $k$ operations will be done.
Let $a=\max(S),b=\operatorname{mex}(S)$. When $k=0$, the answer is $n$. Otherwise if $b>a$, then $b=a+1$ , so $\lceil\frac{a+b}{2}\rceil=b$ . It's not hard to find out that $\max(S\cup\{b\})=b,\operatorname{mex}(S\cup\{b\})=b+1$, so the set $S$ always satisfies $\max(S)+1=\operatorname{mex}(S)$. So the answer is $n+k$ when $b=a+1$. Otherwise $b<a$. So $b<a \Rightarrow 2b<a+b\Rightarrow \frac{a+b}{2}>b\Rightarrow\lceil\frac{a+b}{2}\rceil>b$. In that case $\operatorname{mex}(S)=b$ is always true. So the element we add in all operations is always $\lceil\frac{a+b}{2}\rceil$. Just check whether it is in $S$ at first. The time complexity is $O(n)$ or $O(n \log n)$ for each test case depending on your implementation.
[ "math" ]
1,100
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } template<typename T>void write(T x){ static char q[65];int cnt=0; if(x<0)pc('-'),x=-x; q[++cnt]=x%10,x/=10; while(x) q[++cnt]=x%10,x/=10; while(cnt)pc(q[cnt--]+'0'); } const int maxn=100005; int vis[maxn],a[maxn]; int main(){ int T;read(T); while(T--){ int n,k,MEX=0,MAX=0; read(n),read(k); for(int i=1;i<=n;++i){ read(a[i]); if(a[i]<=n)vis[a[i]]=true; MAX=max(MAX,a[i]); } while(vis[MEX])++MEX; for(int i=1;i<=n;++i){ if(a[i]<=n)vis[a[i]]=false; } int MCX=(MEX+1+MAX)/2; if(MCX>MAX)write(n+k); else{ int ok=false; for(int i=1;i<=n;++i) ok|=(a[i]==MCX); write(n+((k>0)&&!ok)); } pc('\n'); } return 0; }
1497
A
Meximization
You are given an integer $n$ and an array $a_1, a_2, \ldots, a_n$. You should reorder the elements of the array $a$ in such way that the sum of $\textbf{MEX}$ on prefixes ($i$-th prefix is $a_1, a_2, \ldots, a_i$) is maximized. Formally, you should find an array $b_1, b_2, \ldots, b_n$, such that the sets of elements of arrays $a$ and $b$ are equal (it is equivalent to array $b$ can be found as an array $a$ with some reordering of its elements) and $\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$ is maximized. $\textbf{MEX}$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set. For example, $\textbf{MEX}(\{1, 2, 3\}) = 0$, $\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$.
To maximize the sum of $\textbf{MEX}$ on prefixes we will use a greedy algorithm. Firstly we put all unique elements in increasing order to get maximal $\textbf{MEX}$ on each prefix. It is easy to see that replacing any two elements after that makes both $\textbf{MEX}$ and sum of $\textbf{MEX}$ less. In the end we put all elements that are not used in any order because $\textbf{MEX}$ will not change and will still be maximal.
[ "brute force", "data structures", "greedy", "sortings" ]
800
// один манул #include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; sort(a.begin(), a.end()); vector<int> b; for (int i = 0; i < n; i++) { if (i == 0 || a[i] != a[i - 1]) { b.emplace_back(a[i]); } } for (int i = 0; i < n; i++) { if (i > 0 && a[i] == a[i - 1]) { b.emplace_back(a[i]); } } for (auto x : b) cout << x << ' '; cout << '\n'; } return 0; cout << "amogus"; }
1497
B
M-arrays
You are given an array $a_1, a_2, \ldots, a_n$ consisting of $n$ positive integers and a positive integer $m$. You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want. Let's call an array $m$-divisible if for each two adjacent numbers in the array (two numbers on the positions $i$ and $i+1$ are called adjacent for each $i$) their sum is divisible by $m$. An array of one element is $m$-divisible. Find the smallest number of $m$-divisible arrays that $a_1, a_2, \ldots, a_n$ is possible to divide into.
Let's take each number modulo $m$. Now let $cnt_x$ be the amount of $x$ in array $a$. If $cnt_0 \neq 0$, then all $0$ should be put in a single array, answer increases by $1$. For each number $x \neq 0$ we put it in an array $x, m - x, x, m - x, \dots$ In this array the amount of $x$ and the amount of $m - x$ should differ not more than by $1$, that's why we need to make $max(0, |cnt_x - cnt_{m-x}| - 1)$ arrays, containing a single number ($x$ or $m - x$) that is more common.
[ "constructive algorithms", "greedy", "math" ]
1,200
//два манула #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; map<int, int> cnt; while (n--) { int x; cin >> x; cnt[x % m]++; } int ans = 0; for (auto &c : cnt) { if (c.first == 0) ans++; else if (2 * c.first == m) { ans++; } else if (2 * c.first < m || cnt.find(m - c.first) == cnt.end()) { int x = c.second, y = cnt[m - c.first]; ans += 1 + max(0, abs(x - y) - 1); } } cout << ans << '\n'; } return 0; }
1497
C1
k-LCM (easy version)
\textbf{It is the easy version of the problem. The only difference is that in this version $k = 3$.} You are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \ldots, a_k$, such that: - $a_1 + a_2 + \ldots + a_k = n$ - $LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$ Here $LCM$ is the least common multiple of numbers $a_1, a_2, \ldots, a_k$. We can show that for given constraints the answer always exists.
If $n$ is odd, then the answer is $(1, \lfloor \frac{n}{2} \rfloor, \lfloor \frac{n}{2} \rfloor)$ If $n$ is even, but is not a multiple of $4$, then the answer is $(\frac{n}{2} - 1, \frac{n}{2} - 1, 2)$. If $n$ is a multiple of $4$, then the answer is $(\frac{n}{2}, \frac{n}{4}, \frac{n}{4})$.
[ "constructive algorithms", "math" ]
1,200
// три манула #include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { int n, k; cin >> n >> k; if (n % 2) cout << 1 << ' ' << n / 2 << ' ' << n / 2 << '\n'; else if (n % 2 == 0 && n % 4) cout << 2 << ' ' << n / 2 - 1 << ' ' << n / 2 - 1 << '\n'; else cout << n / 2 << ' ' << n / 4 << ' ' << n / 4 << '\n'; } return 0; }
1497
C2
k-LCM (hard version)
\textbf{It is the hard version of the problem. The only difference is that in this version $3 \le k \le n$.} You are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \ldots, a_k$, such that: - $a_1 + a_2 + \ldots + a_k = n$ - $LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$ Here $LCM$ is the least common multiple of numbers $a_1, a_2, \ldots, a_k$. We can show that for given constraints the answer always exists.
In this solution we will reuse the solution for $k = 3$. The answer will be $1, 1, \ldots, 1$ ($k - 3$ times) and the solution $a, b, c$ of the easy version for $n - k + 3$. $(1 + 1 + \ldots + 1) + (a + b + c) = (k - 3) + (n - k - 3) = n$. Also $LCM(1, 1, \ldots, 1, a, b, c) = LCM(a, b, c) \le \frac{n - k + 3}{2} \le \frac{n}{2}$.
[ "constructive algorithms", "math" ]
1,600
// четыре манула #include <bits/stdc++.h> using namespace std; vector<int> solve3(int n) { if (n % 2 == 1) return {1, n / 2, n / 2}; if (n % 4 == 0) return {n / 2, n / 4, n / 4}; if (n % 2 == 0) return {2, n / 2 - 1, n / 2 - 1}; } int main() { int T; cin >> T; while (T --> 0) { int n, k; cin >> n >> k; vector<int> added = solve3(n - k + 3); for (int i = 0; i < k; ++i) { cout << (i <3 ? added[i] : 1) << ' '; // <3 } cout << '\n'; } return 0; }
1497
D
Genius
\textbf{Please note the non-standard memory limit.} There are $n$ problems numbered with integers from $1$ to $n$. $i$-th problem has the complexity $c_i = 2^i$, tag $tag_i$ and score $s_i$. After solving the problem $i$ it's allowed to solve problem $j$ if and only if $\text{IQ} < |c_i - c_j|$ and $tag_i \neq tag_j$. After solving it your $\text{IQ}$ changes and becomes $\text{IQ} = |c_i - c_j|$ and you gain $|s_i - s_j|$ points. Any problem can be the first. You can solve problems in any order and as many times as you want. Initially your $\text{IQ} = 0$. Find the maximum number of points that can be earned.
Let's consider a graph where vertexes are problems and there is an edge $\{i, j\}$ between vertexes $i$ and $j$ with weight $|c_i - c_j|$. Each edge has a unique weight. Let's prove that. Let's assume that $weight = |2^i - 2^j|$ and $i > j$. Then in binary form $weight$ has its $k$-th bit set true if and only if $j \le k < i$. Then for each unique pair $\{i, j\}$ $weight$ is unique too since the corners of a subsegment with true bits are unique. Let $dp_i$ be the maximal amount of points that may be earned ending with problem $i$. Initially $dp_i = 0$ for each $1 \le i \le n$. Let's consider all edges in increasing order (because $\text{IQ}$ should increase). To do that we can consider $j$ in increasing order from $2$ to $n$ and then $i$ in decreasing order from $j - 1$ to $1$. It is also explained by the binary form of the $weight$. Now let's relax $dp$ values. When we consider an edge $\{i, j\}, tag_i \neq tag_j$ we try to solve problem $i$ after solving $dp_j$ problems ending with $j$, and problem $i$ after solving $dp_i$ problems ending with $i$. It means that $dp_i = max(dp_i, dp_j + p), dp_j = max(dp_j, dp_i + p)$ at the same time, where $p = |s_i - s_j|$. After considering all edges the answer is the maximal value among all $dp$ values.
[ "bitmasks", "dp", "graphs", "number theory" ]
2,500
// пять манулов #include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { int n; cin >> n; vector<long long> s(n), tag(n), dp(n, 0); for (int i = 0; i < n; ++i) cin >> tag[i]; for (int i = 0; i < n; ++i) cin >> s[i]; for (int j = 1; j < n; ++j) { for (int i = j - 1; i >= 0; --i) { if (tag[i] == tag[j]) continue; long long dpi = dp[i], dpj = dp[j], p = abs(s[i] - s[j]); dp[i] = max(dp[i], dpj + p); dp[j] = max(dp[j], dpi + p); } } cout << *max_element(dp.begin(), dp.end()) << '\n'; } return 0; }
1497
E1
Square-Free Division (easy version)
\textbf{This is the easy version of the problem. The only difference is that in this version $k = 0$.} There is an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square. Moreover, it is allowed to do at most $k$ such operations before the division: choose a number in the array and change its value to any positive integer. But in this version $k = 0$, so it is not important. What is the minimum number of continuous segments you should use if you will make changes optimally?
For factorization of $x = p_1^{q_1} \cdot p_2^{q_2} \cdot \cdots \cdot p_k^{q_k}$ let's define $mask(x) = p_1^{q_1 \bmod 2} \cdot p_2^{q_2 \bmod 2} \cdot \cdots \cdot p_m^{q_m \bmod 2}$. After that it is easy to see that $x \cdot y$ is a perfect square if and only if $mask(x) = mask(y)$. Now let's say $a_i = mask(a_i)$ for all $1 \le i \le n$. The problem we need to solve is: split the array into minimal amount of non-intersecting subsegments so that on each subsegment all numbers are different. Since $k = 0$ we can do that using a greedy idea. If we consider an element that has not been in our current segment, then we add it to the segment. If it's already taken, then we should end our current segment and start a new one.
[ "data structures", "dp", "greedy", "math", "number theory", "two pointers" ]
1,700
// шесть манулов #include <bits/stdc++.h> using namespace std; const int MAXA = 1e7; vector<int> primes; int mind[MAXA + 1]; int main() { for (int i = 2; i <= MAXA; ++i) { if (mind[i] == 0) { primes.emplace_back(i); mind[i] = i; } for (auto &x : primes) { if (x > mind[i] || x * i > MAXA) break; mind[x * i] = x; } } int T; cin >> T; while (T --> 0) { int n, k; cin >> n >> k; vector<int> a(n, 1); for (int i = 0; i < n; ++i) { int x; cin >> x; int cnt = 0, last = 0; while (x > 1) { int p = mind[x]; if (last == p) { ++cnt; } else { if (cnt % 2 == 1) a[i] *= last; last = p; cnt = 1; } x /= p; } if (cnt % 2 == 1) a[i] *= last; } int L = 0, ans = 1; map<int, int> last; for (int i = 0; i < n; ++i) { if (last.find(a[i]) != last.end() && last[a[i]] >= L) { ++ans; L = i; } last[a[i]] = i; } cout << ans << '\n'; } return 0; }
1497
E2
Square-Free Division (hard version)
\textbf{This is the hard version of the problem. The only difference is that in this version $0 \leq k \leq 20$.} There is an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square. Moreover, it is allowed to do at most $k$ such operations before the division: choose a number in the array and change its value to any positive integer. What is the minimum number of continuous segments you should use if you will make changes optimally?
Let's use the same definitions as in tutorial of E1. So after making $a_i = mask(a_i)$ for all $1 \le i \le n$ we need to split the whole array into minimal amount of contiguous subsegments with all different elements. Also, we can change $k$ elements how we want. Firstly, for each $1 \le i \le n$ and $0 \le j \le k$ let's find $left_{i,j}$ - such minimal index $l$, so that after making $j$ changes the segment $a_l, a_{l + 1}, \ldots, a_i$ contains only distinct values. For fixed $j$ if $i$ is increased then $left_{i,j}$ increases, too, that's why for fixed $j$ we can use the two pointers technique. This allows us to calculate $left_{i,j}$ in $O(n \cdot k)$. Now for each $1 \le i \le n$ and $0 \le j \le k$ let's calculate $dp_{i,j}$ - the minimal amount of contiguous subsegments that prefix $a_1, a_2, \ldots, a_i$ is possible to divide into after making $j$ changes. For each $j$ let's consider $0 \le x \le j$ - the amount of changes on the last subsegment. Let's say that $l = left_{i,x}$ then $dp_{i,j} = min(dp_{i,j}, dp_{l - 1,j-x} + 1)$. This is done in $O(n \cdot k^2)$ so the total complexity of the solution after making $a_i = mask(a_i)$ is $O(n \cdot k^2)$.
[ "data structures", "dp", "greedy", "math", "number theory", "two pointers" ]
2,500
// семь манулов #include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 1; const int MAXA = 1e7; vector<int> primes; int mind[MAXA + 1]; int main() { for (int i = 2; i <= MAXA; ++i) { if (mind[i] == 0) { primes.emplace_back(i); mind[i] = i; } for (auto &x : primes) { if (x > mind[i] || x * i > MAXA) break; mind[x * i] = x; } } vector<int> cnt(MAXA + 1); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; // уже k манулов vector<int> a(n, 1); for (int i = 0; i < n; ++i) { int x; cin >> x; int cnt = 0, last = 0; while (x > 1) { int p = mind[x]; if (last == p) { ++cnt; } else { if (cnt % 2 == 1) a[i] *= last; last = p; cnt = 1; } x /= p; } if (cnt % 2 == 1) a[i] *= last; } vector<vector<int>> mnleft(n, vector<int>(k + 1)); for (int j = 0; j <= k; j++) { int l = n, now = 0; for (int i = n - 1; i >= 0; i--) { while (l - 1 >= 0 && now + (cnt[a[l - 1]] > 0) <= j) { l--; now += (cnt[a[l]] > 0); cnt[a[l]]++; } mnleft[i][j] = l; if (cnt[a[i]] > 1) now--; cnt[a[i]]--; } } vector<vector<int>> dp(n + 1, vector<int>(k + 1, INF)); for (auto &c : dp[0]) c = 0; for (int i = 1; i <= n; i++) { for (int j = 0; j <= k; j++) { if (j > 0) dp[i][j] = dp[i][j - 1]; for (int lst = 0; lst <= j; lst++) { dp[i][j] = min(dp[i][j], dp[mnleft[i - 1][lst]][j - lst] + 1); } } } int ans = INF; for (auto &c : dp.back()) ans = min(ans, c); cout << ans << "\n"; } return 0; }
1498
A
GCD Sum
The $\text{$gcdSum$}$ of a positive integer is the $gcd$ of that integer with its sum of digits. Formally, $\text{$gcdSum$}(x) = gcd(x, \text{ sum of digits of } x)$ for a positive integer $x$. $gcd(a, b)$ denotes the greatest common divisor of $a$ and $b$ — the largest integer $d$ such that both integers $a$ and $b$ are divisible by $d$. For example: $\text{$gcdSum$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$. Given an integer $n$, find the smallest integer $x \ge n$ such that $\text{$gcdSum$}(x) > 1$.
Can you think of the simplest properties that relate a number and its sum of digits? Note that if $X$ is a multiple of 3, then both $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? If $X$ is a multiple of 3, then $\texttt{gcd-sum}(X) \ge 3$. Therefore, we are guaranteed that at least every third number will satisfy the constraints required by our problem $(\texttt{gcd-sum}(X) > 1)$. Therefore, for the input $n$, we can simply check which one of $n$, $n+1$, and $n+2$ has its gcd-sum $> 1$, and print the lowest of them. Note that you must take long long, as input integers exceed the range of int. Moreover, simply outputting $\text{ceil}((n / 3) \times 3)$ is incorrect as some non-multiples of three may also may have gcd-sum $> 1$, for example, 26.
[ "brute force", "math" ]
800
from math import gcd def valid(x): return gcd(x, sum([ord(c) - ord('0') for c in str(x)])) != 1 t = int(input()) while t > 0: t -= 1 n = int(input()) while not valid(n): n += 1 print(n)
1498
B
Box Fitting
You are given $n$ rectangles, each of height $1$. Each rectangle's width is a power of $2$ (i. e. it can be represented as $2^x$ for some non-negative integer $x$). You are also given a two-dimensional box of width $W$. Note that $W$ may or may not be a power of $2$. Moreover, $W$ is at least as large as the width of the largest rectangle. You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles. You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area. See notes for visual explanation of sample input.
There can exist multiple optimal packings for a given set of rectangles. However, all of them can always be rearranged to follow a specific pattern, based on the rectangles' sizes. Can you show that it is always possible to replace a set of consecutive small blocks with a single large block? (of same or larger size) We follow a greedy strategy: Initialize height of box as 1. Initialize current layer size as $W$. Pick the largest available rectangle that can fit into the current layer, and place it there. Repeat until this layer cannot fit any more rectangles. If more rectangles remain, increment height by 1 and now repeat the last three steps. Else, output the current value of height. First count sort the given rectangles based on their widths. There can only be 20 distinct rectangle widths in the range $[1, 10^9]$, so the following works: The solution can be implemented by iterating $N$ times. At each iteration, step through the counts array and take the largest available rectangle that can fit into the current space. If no rectangle was able to fit, increment height by 1 and reset box width to $W$. This has complexity $\mathcal{O}(n\log(w_\text{max}))$. It is also possible to implement the solution with a multiset and upper_bound, for a complexity of $\mathcal{O}(n\log(n))$. Store all rectangle sizes in a multiset. At each iteration, find using upper_bound the largest rectangle that can fit into the current space we have, and fit it in. If no rectangle can fit in this space, reset the space to maximum, increment height, and repeat. It is always possible to replace several smaller blocks with a single larger block if it is available. Because all blocks are powers of two, it must so happen that smaller powers of two will sum to a larger power. Therefore, we can always place a larger block first if it can be placed there. This elaborate proof isn't actually required for solving the problem. The intuition in the brief proof is sufficient for solving the problem. This proof is for correctness purpose only. Let's first note a property: if $a_1 + \ldots + a_n>a_0$, then there exists some $i$ such that $a_1+ \ldots +a_i=a_0$, when all $a_i$ are powers of 2 AND $a_1$ to $a_n$ is a non-increasing sequence (AND $a_1 <= a_0$, of course). Why is this so? You can take an example and observe this intuitively, this is a common property of powers of two. For example, $4+2+2+1+1>8$, but $4+2+2$ (prefix) $=8$. Formally: if $a_1 =a_0$, this property is trivially true. If $a_1 < a_0$, we can splilt $a_0=2^ka_1$ for some $k$ into $2^k$ parts and - by strong induction - claim this property holds. Let us now compare some optimal solution and our greedy solution. Before comparing, we first sort all blocks in each layer of the optimal solution in decreasing order. This does not affect the final answer but helps in our comparison. This comparison goes from bottom to top, left to right. Let us look at the first point of difference: when the block placed by us ($B_G$) is different from the block placed by the optimal solution ($B_O$). There are three cases. If $B_O > B_G$: this is impossible, as in our greedy solution, we are always placing the largest possible block. We wouldn't place $B_G$ in there if $B_O$ was also possible. If $B_O == B_G$: we have nothing to worry about (this isn't a point of difference) If $B_O < B_G$: let us assume that the optimal solution places several consecutive small blocks, and not just one $B_O$. Since the blocks are in decreasing order, none of them would be bigger than $B_G$. Note that either all of these blocks will sum to less than $B_G$ or a prefix of them will be exactly equal to $B_G$. In either case, we can swap them with one single large block $B_G$ (swapping with a $B_G$ which was placed in some higher layer in the optimal solution) Hence, in the last case, we have shown that any optimal solution (an arrangement of blocks) can be rearranged such that each layer fits the largest possible block first. This is also what is done in our greedy strategy. Therefore, with this proof by rearrangement, we conclude that our greedy strategy gives the same minimum height as that of the optimal answer. There is a binary search method to solve this problem. We binary search for the minimum height required. Given a height $h$ - how to check if it can fit all rectangles? We first preprocess the given array to construct a new array $c_i$ = number of rectangles of width $1 << i$. The size of this array is < 20. We iterate from largest width to smallest width. Let its width is $w_i$. Then, we know that it fits only $W / w_i$ times in one layer. Therefore, with height $h$, the box can only fit in $f_i = h \times (W / w_i)$. So, we can say that if $f_i < c_i$, then this height is insufficient. Therefore, we now know that for any $i$, if $f_i < c_i$, then the height is insufficient. Do we need more conditions to provably state that the given height is sufficient? Yes! We also need to check if we can fit in the $i$-th block in combination with tthe $i+1$-th block. That is, when checking if the $i$-th block has enough space, we need to account for the space that has already been used by the $i + 1$-th block. So, we need to update $c_i = c_i + 2\times c_{i+1} + 4\times c_{i+2} \ldots$. Therefore, we only need to compute the suffix sum $c_i$ like so and then check the above conditions. Complexity is $\mathcal{O}(n+\log(w_{max})\log(n))$. As we understood in the proof, this solution only works when it's guaranteed that smaller blocks will always exactly sum to any larger block. Therefore, if the blocks are not powers of two, this guarantee does not hold. The following counterexample suffices: As you can see here the smaller blocks are not guaranteed to sum to the larger block (no prefix of $4,3,3$ sums to $6$). Our greedy solution gives minimum height 3, but best possible minimum height is $2$ (first layer: $6,4,3$, second layer: $6,4,3$)
[ "binary search", "bitmasks", "data structures", "greedy" ]
1,300
#include <array> #include <cassert> #include <cmath> #include <iostream> using namespace std; #define PW 20 array<int, PW> arr; int n, w; bool valid(int height) { for (int pw = 0; pw < PW; pw++) { long long units_i_have = 1ll * height * (w / (1 << pw)); if (units_i_have < arr[pw]) return false; } return true; } int main() { int t; cin >> t; while (t--) { cin >> n >> w; for (int i = 0; i < PW; i++) arr[i] = 0; for (int _ = 0; _ < n; _++) { int w; cin >> w; arr[log2(w)] += 1; } // suffix cumulative count for (int i = PW - 2; i >= 0; i--) arr[i] += 2 * arr[i + 1]; int beg = 1, end = n, ans = -1; while (beg <= end) { int mid = (beg + end) / 2; if (valid(mid)) { end = mid - 1; ans = mid; } else { beg = mid + 1; } } assert(ans != -1); cout << ans << endl; } }
1498
C
Planar Reflections
Gaurang has grown up in a mystical universe. He is faced by $n$ consecutive 2D planes. He shoots a particle of decay age $k$ at the planes. A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age $k-1$. If a particle has decay age equal to $1$, it will NOT produce a copy. For example, if there are two planes and a particle is shot with decay age $3$ (towards the right), the process is as follows: (here, $D(x)$ refers to a single particle with decay age $x$) - the first plane produces a $D(2)$ to the left and lets $D(3)$ continue on to the right; - the second plane produces a $D(2)$ to the left and lets $D(3)$ continue on to the right; - the first plane lets $D(2)$ continue on to the left and produces a $D(1)$ to the right; - the second plane lets $D(1)$ continue on to the right ($D(1)$ cannot produce any copies). In total, the final multiset $S$ of particles is $\{D(3), D(2), D(2), D(1)\}$. (See notes for visual explanation of this test case.) Gaurang is unable to cope up with the complexity of this situation when the number of planes is too large. Help Gaurang find the size of the multiset $S$, given $n$ and $k$. Since the size of the multiset can be very large, you have to output it modulo $10^9+7$. Note: Particles can go back and forth between the planes without colliding with each other.
We can use dynamic programming to store the state of the simulation at a given time. Therefore, we can simulate the entire situation by reusing the dp states. I will describe the most intuitive solution. Naturally, looking at the constraints as well as at the output that is required, we can store a 3-state dp: dp[n][k][2]. Here, dp[n][k][d] indicates the total number of particles (at the end of the simulation) when one particle of decay age $k$ hits the $n$-th plane in the direction $d$. ($d$ is either $0$ or $1$, and indicates the direction (left/right) in which the particle is going) There can be two directions, $N$ planes and maximum decay age is $K$. So, this dp requires $2\times1000\times1000\times4$ bytes $\approx 24MB$ which is well within our memory constraints. How to update the DP states? If $k = 1$, the value of dp[n][1][d] for any $n$ or $d$ is obviously $1$ (as no copies are produced). So, let us consider a particle $P$ with $k>1$. This particle $P$ produces a copy $P'$ going in the opposite direction. We can count the number of particles produced by $P'$ as dp[n - 1][k - 1][1 - d], as it hits the previous plane with a smaller decay age and in the opposite direction. Moreover, the particle $P$ itself hits the next plane and continues to produce more stuff. We can calculate its number of particles produced as dp[n + 1][k][d], as it hits the next plane with the same decay age and the same direction! Finally, we can combine these two values to get the value of dp[n][k][d]. We can implement this is easily as a recursive dp with memoization. At each state, we only need to iterate in the correct order (in one case, from right to left, and in the other, from left to right), and update states as required. Look at the implementation for more details. The total complexity of this algorithm is $\mathcal{O}(nk)$ Obviously, there exist much better solutions which do not use a third state and are much sleaker. However, I wanted to describe the simplest idea required to solve the problem.
[ "brute force", "data structures", "dp" ]
1,600
mod = int(1e9 + 7) def iter_solver(N, K): dp = [[[-1 for _ in range(2)] for __ in range(K + 1)] for ___ in range(N + 1)] for i in range(1, N + 1): dp[i][1][0] = dp[i][1][1] = 1 for k in range(2, K + 1): # forward dir for n in range(N, 0, -1): ans = 2 if n < N: ans += dp[n + 1][k][0] - 1 ans %= mod if n > 1: ans += dp[n - 1][k - 1][1] - 1 ans %= mod dp[n][k][0] = ans # backward dir for n in range(1, N + 1): ans = 2 if n < N: ans += dp[n + 1][k - 1][0] - 1 ans %= mod if n > 1: ans += dp[n - 1][k][1] - 1 ans %= mod dp[n][k][1] = ans return dp[1][K][0] t = int(input()) while t > 0: t -= 1 n, k = list(map(int, input().split())) print(iter_solver(n, k))
1498
D
Bananas in a Microwave
You have a malfunctioning microwave in which you want to put some bananas. You have $n$ time-steps before the microwave stops working completely. At each time-step, it displays a new operation. Let $k$ be the number of bananas in the microwave currently. Initially, $k = 0$. In the $i$-th operation, you are given three parameters $t_i$, $x_i$, $y_i$ in the input. Based on the value of $t_i$, you must do one of the following: \textbf{Type 1}: ($t_i=1$, $x_i$, $y_i$) — pick an $a_i$, such that $0 \le a_i \le y_i$, and perform the following update $a_i$ times: $k:=\lceil (k + x_i) \rceil$. \textbf{Type 2}: ($t_i=2$, $x_i$, $y_i$) — pick an $a_i$, such that $0 \le a_i \le y_i$, and perform the following update $a_i$ times: $k:=\lceil (k \cdot x_i) \rceil$. Note that \textbf{$x_i$ can be a fractional value}. See input format for more details. Also, $\lceil x \rceil$ is the smallest integer $\ge x$. At the $i$-th time-step, you must apply the $i$-th operation exactly once. For each $j$ such that $1 \le j \le m$, output the earliest time-step at which you can create \textbf{exactly} $j$ bananas. If you cannot create \textbf{exactly} $j$ bananas, output $-1$.
We have a brute force $\mathcal{O}(N\cdot M^2)$ solution. At every timestep $t$, for each banana $b_i$ that has already been reached previously, apply this timestep's operation $y_t$ times on $b_i$. For all the $y_t$ bananas reachable from $b_i$, update their minimum reachability time if they hadn't been reached previously. Why is this correct? Simply because we are simulating each possible step of the algorithm exactly as it is described. Therefore, we cannot get an answer that's better or worse than that of the optimal solution. Observe if we can reduce our search space when we visit nodes that have already been visited previously. Let us take an example. We have some timestep $t,x,y = 1,5,10$. If we start visiting from $k=10$, we will visit $k=15,20,\ldots,55,60$. Let us say that $k=40$ was an already visited state. Do we now need to continue visiting $k=45,\ldots,60$ or can we stop our search here? We can actually stop our search as soon as we reach a previouly visited node! Why is this so? This is because - within the same iteration - that already visited node will once again start its own search, and will hit all the points that we were going to hit, and some more! For example, let us say we would reach points $a, a\cdot x, a\cdot x^2, \ldots, a\cdot x^{y-1}$. Now, assume that $a\cdot x^5$ had been previously reached, then it is better to stop at $a\cdot x^5$, as this node itself will reach $a\cdot x^5, a\cdot x^6, \ldots, a\cdot x^{y-2}, a\cdot x^{y-1},a\cdot x^{y}, \ldots, a\cdot x^{5+y-1}$. Note the latter range includes as a prefix the entire remaining suffix of the former range! Therefore, in this approach, nodes that would have been visited, will eventually be visited, and get assigned the minimum timestamp. We can implement the optimized solution by simply adding an extra if already_visited[k]: break to our inner loop. Yup, really, that's all it takes to solve this question! Complexity analysis: We can show that each node is visited at most twice: an unvisited node is reached atmost once, whereas a visited node is reached atmost twice (once during the main loop and once when searching from the immediately previous visited node) There are $N$ iterations, and in each iteration, each of the $M$ nodes is visited at most twice. Therefore, the total complexity is $\mathcal{O}(2NM)$. Integer overflows: $x'$ does not fit in integer range Out of bounds access: simulating the $y_t$ steps of the algorithm even when $k$ exceeds $M$ prematurely
[ "dfs and similar", "dp", "graphs", "implementation" ]
2,200
import sys input = lambda: sys.stdin.readline().rstrip() DIV = int(1e5) def ceil(x, y): return (x + y - 1) // y T, M = list(map(int, input().split())) is_seen = [0 for _ in range(M + 1)] is_seen[0] = 1 answer = [-1 for _ in range(M + 1)] answer[0] = 0 o = 0 for timestep in range(1, T + 1): t, x, y = list(map(int, input().split())) def operation(val): if t == 1: return curr + ceil(x, DIV) else: return ceil(curr * x, DIV) k = 0 setting = [] while k <= M: if is_seen[k]: curr = k i = 0 while i < y: i += 1 o += 1 curr = operation(curr) if curr > M: break if is_seen[curr]: break setting.append(curr) answer[curr] = timestep k += 1 for idx in setting: is_seen[idx] = 1 sys.stdout.write(" ".join(map(str, answer[1:])))
1498
E
Two Houses
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307. There is a city in which Dixit lives. In the city, there are $n$ houses. There is \textbf{exactly one directed road between every pair of houses.} For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the $i$-th house is $k_i$. Two houses A and B are bi-reachable if A is reachable from B \textbf{and} B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of $|k_A - k_B|$, where $k_i$ is the number of roads leading to the house $i$. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are \textbf{not} given the direction of each road. You are given — for each house — only the number of incoming roads to that house ($k_i$). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is \textbf{no upper limit on the number of queries}. But, \textbf{you cannot ask more queries after the judge answers "Yes" to any of your queries.} Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details.
In this problem we have to output two nodes $a$ and $b$ such that there is a path from $a$ to $b$ and $b$ to $a$ and the absolute value of the difference of the indegree $(|k_a - k_b|)$ should be maximum. First of all, let us think of bireachability only i.e how to find two nodes $a$ and $b$ such that they are both reachable from each other? How can we verify this from the judge? Because if we ask $"? \ a \ b"$ i.e whether there is a path from $a$ to $b$ or not, then if the judge answers "Yes", we can't ask further queries. So we have to ask queries for those pairs $(a,b)$ for which we are sure that there is a path from $b$ to $a$. So how to ensure whether there is a path from $b$ to $a$ or not? The answer lies in the fact that the given graph is not an ordinary graph, it is a special one. For every pair of vertices in this graph, there is a directed edge. So this type of graph has some interesting properties which we are going to see now. Image how the compressed SCC of the graph will look like. For every pair of nodes of compressed SCC, there will be an edge, so it will have exactly one source, one sink and there would be only one possible topological sorting of this compressed SCC. Since there is an edge between every pair of nodes, for every pair of nodes in the compresses SCC also, there would be an edge. And we know that if there is an edge between node $a$ to node $b$, then node $a$ comes before node $b$ in the topological sort. So for every pair of nodes of compressed SCC, we know which node would come first in the topological sorting, so it would result in a unique topological sorting. Now we'll see one interesting and important property of this graph. Property: Consider two consecutive strongly connected components in the topological sorting, then all nodes present in the left component will have indegree strictly less than all nodes present in the right component. Here left denotes lower enumeration in the topological sorting. Consider two nodes $u$ and $v$ from the left component and right component respectively. Since the contribution to the indegree from the nodes which don't lie in these two components would be the same for both $u$ and $v$ (because $u$ and $v$ lie in adjacent components), we are ignoring it as we have to just compare their values. If we consider all the edges between the nodes of the left component and the right component, then all of them would be directed from the node in the left component to the node in the right component. So the node $v$ would have minimum indegree of $Size of Left Component$. The node $u$ would have the maximum indegree of $Size of Left Component - 1$. This is because there is no edge directed from the right component to the node $u$ and the maximum indegree will be when all other nodes in the left component have an edge directed towards node $u$. In that case, it would be $Size of Left Component -1$. So the indegree of $u$ is strictly less than the indegree of $v$. Since $u$ and $v$ are arbitrary nodes, it is true for all pairs of nodes. Using the above property we can argue that if indegree of node $a$ is greater than the indegree of node $b$, then node $a$ is reachable from node $b$. Because either node $a$ lies in the same SCC or to the SCC of higher enumeration in topological sorting. In both cases $a$ is reachable from $b$. So we can store all pairs of nodes $(a,b), 1 \leq a \leq n, 1 \leq b \leq n, a < b$ in an array and sort it according to decreasing order of absolute value of difference of indegrees i.e $|k_a - k_b|$. And if we pick a pair, let it be ($a$,$b$) and $indegree[b] > indegree[a]$, then we are sure that $b$ is reachable from $a$ so we need to check whether $a$ is reachable from $b$ or not, so we ask $"? \ b \ a"$ and if the judge responds by "Yes", then it means both $a$ and $b$ are reachable from each other. Since we were iterating in the decreasing order of $|k_a - k_b|$, we get the optimal answer. If the judge never outputs "Yes" in the whole process, then there is no pair of nodes that are reachable from each other. So we will output $"? \ 0 \ 0"$ Overall Complexity : $O(n^2 \log_2 n)$
[ "brute force", "graphs", "greedy", "interactive", "sortings" ]
2,200
import sys input = lambda: sys.stdin.readline().rstrip() n = int(input()) indegs = list(map(int, input().split())) pairs = [] for i in range(n): for j in range(i + 1, n): if indegs[i] > indegs[j]: pairs.append((indegs[i] - indegs[j], (i, j))) else: pairs.append((indegs[j] - indegs[i], (j, i))) pairs = sorted(pairs, reverse=True) l = len(pairs) for _, nodes in pairs: ni, nj = nodes sys.stdout.write(f"? {ni + 1} {nj + 1}\n") sys.stdout.flush() s = input() if s == "Yes": sys.stdout.write(f"! {ni + 1} {nj + 1}\n") exit(0) sys.stdout.write("! 0 0\n")
1498
F
Christmas Game
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has $n$ nodes (numbered $1$ to $n$, with some node $r$ as its root). There are $a_i$ presents are hanging from the $i$-th node. Before beginning the game, a special integer $k$ is chosen. The game proceeds as follows: - Alice begins the game, with moves alternating each turn; - in any move, the current player may choose some node (for example, $i$) which has depth at least $k$. Then, the player picks some positive number of presents hanging from that node, let's call it $m$ $(1 \le m \le a_i)$; - the player then places these $m$ presents on the $k$-th ancestor (let's call it $j$) of the $i$-th node (the $k$-th ancestor of vertex $i$ is a vertex $j$ such that $i$ is a descendant of $j$, and the difference between the depth of $j$ and the depth of $i$ is exactly $k$). Now, the number of presents of the $i$-th node $(a_i)$ is decreased by $m$, and, correspondingly, $a_j$ is increased by $m$; - Alice and Bob both play optimally. The player unable to make a move loses the game. \textbf{For each possible root} of the tree, find who among Alice or Bob wins the game. Note: The depth of a node $i$ in a tree with root $r$ is defined as the number of edges on the simple path from node $r$ to node $i$. The depth of root $r$ itself is zero.
By the Sprague-Grundy theorem, we know that the current player has a winning strategy if $a_1 \oplus a_2 \oplus \ldots \oplus a_n$ (xorsum of sizes of the existing piles) is non-zero. For a proof, read details on CP-algorithms. Let us classify nodes into odd or even depending on their depth relative to the root. Note that even steps do not affect the game state. Let us prove how: Let us say it's Alice's turn. If Alice moves some coins from an even step to an odd step, then Bob can move exactly those same coins from that odd step back to an even step. After this transition, once again it's Alice's move. In fact, we realize that Bob can "revert" every even->odd move by Alice. Therefore, if Alice wants to win, she has to play at least one odd->even move. Moves that go from even->odd do not affect the game state at all, as the other player can always play another move that reverts them. Therefore, we can say that any coins present on even steps will not change the game state. Let us now analyze what happens if some coins move from the odd steps to even steps. We know that any coins on even nodes will not contribute to the game state. In fact, we realize that it does not matter whether these coins were present on the even nodes before the game started or whether they came by on the even nodes during the game. Once they are on an even step, they no longer contribute to the game state. Hence, we can conclude that moving a coin from odd step to an even step is as good as taking a coin from the odd step and throwing it away. As we can see, we have effectively reduced the Nim game on tree to a linear nim game where only the odd positioned nodes determine the winning strategy. This is known as the staircase nim. The result is the following: the current player has a winning strategy if xorsum of all values at the odd steps is non-zero. In general $K$, we can extend this idea to: parity of $d' = \lfloor \frac d K \rfloor$ where $d$ is the depth of this node (zero-indexed). All nodes - such that $d'$ is odd for them - will contribute to the final xorsum. Take a moment to digest this. How to calculate these xors? At each node $x$, we store a vector of size $D(n) = 2\cdot K$ where $D(n)_i$ is the xorsum of all nodes having their depth = $i$ - relative to node $x$ - in the subtree of node $n$. How to propagate these values in a DFS? We know that the nodes at depth i is at depth i + 1 for my child nodes. So, we can simply cycle through them and update the values. Check the implementation for details.
[ "bitmasks", "data structures", "dfs and similar", "dp", "games", "math", "trees" ]
2,500
n, k = list(map(int, input().split())) k2 = 2 * k dp = [[0 for _ in range(k2)] for _ in range(n + 1)] adj = [[] for _ in range(n + 1)] for _ in range(n - 1): _x, _y = list(map(int, input().split())) adj[_x].append(_y) adj[_y].append(_x) a = [0] + list(map(int, input().split())) win = [0 for _ in range(n + 1)] parent = [0 for _ in range(n + 1)] def dfs(node): global parent global dp stack = [node] pass_num = [0 for _ in range(n + 1)] while stack: node = stack[-1] pass_num[node] += 1 if pass_num[node] == 1: for neigh in adj[node]: if neigh == parent[node]: continue parent[neigh] = node stack.append(neigh) continue dp[node][0] = a[node] stack.pop() for neigh in adj[node]: if neigh == parent[node]: continue for rem in range(1, k2): dp[node][rem] ^= dp[neigh][rem - 1] dp[node][0] ^= dp[neigh][k2 - 1] def dfs2(node): global win stack = [[node, [0 for __ in range(k2)]]] global dp while stack: node, prev_xors = stack[-1] stack.pop() final_xors = [x ^ y for x, y in zip(prev_xors, dp[node])] for neigh in adj[node]: if neigh == parent[node]: continue send_xors = [x for x in final_xors] for i in range(1, k2): send_xors[i] ^= dp[neigh][i - 1] send_xors[0] ^= dp[neigh][k2 - 1] send_xors = [send_xors[-1]] + send_xors[:-1] stack.append([neigh, send_xors]) odd_xor = 0 for i in range(k, k2): odd_xor ^= final_xors[i] win[node] = 1 if odd_xor > 0 else 0 dfs(1) dfs2(1) print(" ".join(list(map(str, win[1:]))))
1499
A
Domino on Windowsill
You have a board represented as a grid with $2 \times n$ cells. The first $k_1$ cells on the first row and first $k_2$ cells on the second row are colored in white. All other cells are colored in black. You have $w$ white dominoes ($2 \times 1$ tiles, both cells are colored in white) and $b$ black dominoes ($2 \times 1$ tiles, both cells are colored in black). You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino. Can you place all $w + b$ dominoes on the board if you can place dominoes both horizontally and vertically?
We can prove that if we have $k_1 + k_2$ white cells on the board then we can place any $w$ white dominoes as long as $2w \le k_1 + k_2$. The proof is the following: if $k_1 \ge k_2$ let's place one domino at position $((1, k_1 - 1), (1, k_1))$, otherwise let's place domino at position $((2, k_2 - 1), (2, k_2))$. Then we can solve the placement of $w - 1$ dominoes in $k_1 - 2$ cells in the first row and $k_2$ cells of the second row recursively (or, analogically, $k_1$ and $k_2 - 2$). At the end, either all dominoes are placed or $k_1 < 2$ and $k_2 < 2$. If $k_1 = 0$ or $k_2 = 0$ then, since $2w \le k_1 + k_2$, then $w = 0$ or we successfully placed all dominoes. If $k_1 = 1$ and $k_2 = 1$ then we, possibly, need to place one domino more - and we can place it vertically. We can prove that we can place any $b$ dominoes as long as $2b \le (n - k_1) + (n - k_2)$ in the same manner. As a result, all we need to check is that $2w \le k_1 + k_2$ and $2b \le (n - k_1) + (n - k_2)$.
[ "combinatorics", "constructive algorithms", "math" ]
800
fun main() { repeat(readLine()!!.toInt()) { val (n, k1, k2) = readLine()!!.split(' ').map { it.toInt() } val (w, b) = readLine()!!.split(' ').map { it.toInt() } if (k1 + k2 >= 2 * w && (n - k1) + (n - k2) >= 2 * b) println("YES") else println("NO") } }
1499
B
Binary Removals
You are given a string $s$, consisting only of characters '0' or '1'. Let $|s|$ be the length of $s$. You are asked to choose some integer $k$ ($k > 0$) and find a sequence $a$ of length $k$ such that: - $1 \le a_1 < a_2 < \dots < a_k \le |s|$; - $a_{i-1} + 1 < a_i$ for all $i$ from $2$ to $k$. The characters at positions $a_1, a_2, \dots, a_k$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $a$ should not be adjacent. Let the resulting string be $s'$. $s'$ is called sorted if for all $i$ from $2$ to $|s'|$ $s'_{i-1} \le s'_i$. Does there exist such a sequence $a$ that the resulting string $s'$ is sorted?
There are several different ways to solve this problem. In my opinion, the two easiest solutions are: notice that, in the sorted string, there is a prefix of zeroes and a suffix of ones. It means that we can iterate on the prefix (from which we remove all ones), and remove all zeroes from the suffix we obtain. If we try to remove two adjacent characters, then we cannot use this prefix; if there is a substring 11 before the substring 00 in our string, then from both of the substrings, at least one character remains, so if the first occurrence of 11 is earlier than the last occurrence of 00, there is no answer. Otherwise, the answer always exists.
[ "brute force", "dp", "greedy", "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int i = s.find("11"); int j = s.rfind("00"); cout << (i != -1 && j != -1 && i < j ? "NO" : "YES") << endl; } }
1499
C
Minimum Grid Path
Let's say you are standing on the $XY$-plane at point $(0, 0)$ and you want to reach point $(n, n)$. You can move only in two directions: - to the right, i. e. horizontally and in the direction that increase your $x$ coordinate, - or up, i. e. vertically and in the direction that increase your $y$ coordinate. In other words, your path will have the following structure: - initially, you choose to go to the right or up; - then you go some \textbf{positive integer} distance in the chosen direction (distances can be chosen independently); - after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than $n - 1$ direction changes. As a result, your path will be a polygonal chain from $(0, 0)$ to $(n, n)$, consisting of \textbf{at most} $n$ line segments where each segment has positive integer length and vertical and horizontal segments alternate. Not all paths are equal. You have $n$ integers $c_1, c_2, \dots, c_n$ where $c_i$ is the cost of the $i$-th segment. Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $k$ segments ($k \le n$), then the cost of the path is equal to $\sum\limits_{i=1}^{k}{c_i \cdot length_i}$ (segments are numbered from $1$ to $k$ in the order they are in the path). Find the path of the minimum cost and print its cost.
Suppose we decided to make exactly $k - 1$ turns or, in other words, our path will consist of exactly $k$ segments. Since we should finish at point $(n, n)$ and vertical and horizontal segments alternates, then it means that $length_1 + length_3 + length_5 + \dots = n$ and $legth_2 + length_4 + length_6 + \dots = n$. From the other side we should minimize $\sum\limits_{i=1}^{k}{c_i \cdot length_i}$. But it means that we can minimize $c_1 \cdot length_1 + c_3 \cdot length_3 + \dots$ and $c_2 \cdot length_2 + c_4 \cdot length_4 + \dots$ independently. How to minimize $c_1 \cdot length_1 + c_3 \cdot length_3 + \dots$ if we know that $length_1 + length_3 + length_5 + \dots = n$ and $length_i \ge 1$? It's easy to prove that it's optimal to assign all $length_i = 1$ except minimum $c_i$ and assign to this minimum $c_i$ the remaining part $length_i = n - cntOdds + 1$. In other words, to calculate the optimal path consisting of $k$ segments, we need to know the sum of $c_i$ on odd and even positions among $c_1, \dots, c_k$ and also minimum $c_i$ among odd and even positions. Then we can drive out the answer as a quite easy formula $sumOdd + minOdd \cdot (n - cntOdd)$ $+$ $sumEven + minEven \cdot (n - cntEven)$. Finally, we should iterate over all $k$ from $2$ to $n$ and find the minimum answer among all variants. It's easy to recalculate sums and minimums when we make transition form $k$ to $k + 1$. Complexity is $O(n)$.
[ "brute force", "data structures", "greedy", "math" ]
1,500
fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val c = readLine()!!.split(' ').map { it.toInt() } val mn = intArrayOf(1e9.toInt(), 1e9.toInt()) val rem = longArrayOf(n.toLong(), n.toLong()) var sum = 0L var ans = 1e18.toLong() for (i in c.indices) { mn[i % 2] = minOf(mn[i % 2], c[i]) rem[i % 2]-- sum += c[i] if (i > 0) { val cur = sum + rem[0] * mn[0] + rem[1] * mn[1] ans = minOf(ans, cur) } } println(ans) } }
1499
D
The Number of Pairs
You are given three positive (greater than zero) integers $c$, $d$ and $x$. You have to find the number of pairs of positive integers $(a, b)$ such that equality $c \cdot lcm(a, b) - d \cdot gcd(a, b) = x$ holds. Where $lcm(a, b)$ is the least common multiple of $a$ and $b$ and $gcd(a, b)$ is the greatest common divisor of $a$ and $b$.
Let's represent $a$ as $Ag$ and $b$ as $Bg$, where $g=gcd(a,b)$ and $gcd(A,B)=1$. By definition $lcm(a,b) = \frac{ab}{g}$, so we can represent $lcm(a,b)$ as $\frac{Ag \cdot Bg}{g} = ABg$. Now we can rewrite the equation from the statement as follows: $c \cdot ABg - d \cdot g = x \implies g(c \cdot AB - d) = x$. Since the left-hand side is divisible by $g$, the right-hand side should also be divisible. So we can iterate over $g$ as divisors of $x$. If the right-hand side of $c \cdot AB = \frac{x}{g} + d$ is not divisible by $c$ then we can skip such $g$. $AB = \frac{\frac{x}{g}+d}{c}$ (let's denote as $k$). If $k$ has some prime divisor $p$ then exactly one of $A$ and $B$ should be divisible by $p$ because $gcd(A,B)=1$ ($A$ and $B$ have no common divisors). So there are $2^{\textit{the number of prime divisors of k}}$ pairs of $A$ and $B$ for current value of $g$. We can precalculate the minimum prime divisor for each number up to $2 \cdot 10^7$ (the maximum value of $k$ that you may need) in $O(2 \cdot 10^7 \log{\log{(2 \cdot 10^7)}})$ using Eratosthenes sieve. Now we can solve the problem in $O(\sqrt{x}\log{x})$ for each testcase, but that's not fast enough. To speed up this approach, we can precalculate the number of prime divisors for each number up to $2 \cdot 10^7$. Let's denote $mind_i$ as the minimum prime divisor of $i$ and $val_i$ as the number of prime divisors of $i$. Then $val_i = val_{i / mind_i}$ plus $1$ if $mind_i \neq mind_{i / mind_i}$. Now, to solve the problem, we only need to iterate over the divisors of $x$, so the time complexity is $O(\sqrt{x})$ per testcase.
[ "dp", "math", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 2e7 + 13; int main() { vector<int> mind(N, -1), val(N); mind[1] = 1; for (int i = 2; i < N; ++i) if (mind[i] == -1) for (int j = i; j < N; j += i) if (mind[j] == -1) mind[j] = i; for (int i = 2; i < N; ++i) { int j = i / mind[i]; val[i] = val[j] + (mind[i] != mind[j]); } int t; scanf("%d", &t); while (t--) { int c, d, x; scanf("%d%d%d", &c, &d, &x); int ans = 0; for (int i = 1; i * i <= x; ++i) { if (x % i != 0) continue; int k1 = x / i + d; if (k1 % c == 0) ans += 1 << val[k1 / c]; if (i * i == x) continue; int k2 = i + d; if (k2 % c == 0) ans += 1 << val[k2 / c]; } printf("%d\n", ans); } }
1499
E
Chaotic Merge
You are given two strings $x$ and $y$, both consist only of lowercase Latin letters. Let $|s|$ be the length of string $s$. Let's call a sequence $a$ a merging sequence if it consists of exactly $|x|$ zeros and exactly $|y|$ ones in some order. A merge $z$ is produced from a sequence $a$ by the following rules: - if $a_i=0$, then remove a letter from the beginning of $x$ and append it to the end of $z$; - if $a_i=1$, then remove a letter from the beginning of $y$ and append it to the end of $z$. Two merging sequences $a$ and $b$ are different if there is some position $i$ such that $a_i \neq b_i$. Let's call a string $z$ chaotic if for all $i$ from $2$ to $|z|$ $z_{i-1} \neq z_i$. Let $s[l,r]$ for some $1 \le l \le r \le |s|$ be a substring of consecutive letters of $s$, starting from position $l$ and ending at position $r$ inclusive. Let $f(l_1, r_1, l_2, r_2)$ be the number of different merging sequences of $x[l_1,r_1]$ and $y[l_2,r_2]$ that produce chaotic merges. Note that only non-empty substrings of $x$ and $y$ are considered. Calculate $\sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2)$. Output the answer modulo $998\,244\,353$.
First, let's try to calculate the number of merging sequences just for some fixed pair of strings $x$ and $y$. Imagine we build a merge letter by letter. So far $i$ letters are in the merge already. For the $(i+1)$-th letter we can pick a letter from either string $x$ or string $y$ (put a $0$ or a $1$ into the merging sequence, respectively). What constraints our choice? Easy to see that it's only the $i$-th letter of the merge. So we can come up with the following dynamic programming. $dp[i][j][c]$ is the number of merging sequences such that $i$ characters from $x$ are taken, $j$ characters from $y$ are taken and the last character of the merge is $c$. $c$ can be either just a letter (a dimension of size $26$) or an indicator of a string the last character was taken from ($0$ for string $x$ and $y$ from string $y$). Since we know how many characters are taken from each string, we can easily decide the last taken character from that indicator. For each transition we can just take a character from either of the strings. The sum of $dp[|x|][|y|][i]$ over all $i$ will be the total number of merging sequences. Now for the substrings. Recall the following definition of a substring: $b$ is a substring of $a$ if you can remove some characters from the beginning of $a$ (possibly, none or all) and some characters from the end of $a$ (possibly, none or all) to get the string $b$. What if we incorporated that definition into our dynamic programming? Let $dp[i][j][c]$ be the number of merging sequences that end exactly before the $i$-th character of $x$, exactly before the $j$-th character of $y$ and the last character is still $c$. How to remove some characters from the beginning? That actually is the same as attempting to start the merge from every state of dp. So, if we are currently in some state $dp[i][j][c]$, then we can act as if we have just taken the $i$-th character of $x$ or the $j$-th character of $y$ as the first character of the merge. How to remove some characters from the end? Since $dp[i][j][c]$ is the number of merging sequences that end exactly there, why not just sum up all the values of dynamic programming into the answer? We will count the sequences that end in all possible positions of both strings. That is almost the answer to the task. The only issue we have is that we forgot the condition that asks us to get a non-empty substring from each string. Well, there are multiple ways to resolve the issue. We can remove bad sequences afterwards: their count is the number of chaotic substrings of $x$ multiplied by all possible empty substrings of $y$ (there are $|y|+1$ of them) plus the same thing for $y$ and $x$. These can be counted with two pointers. Alternatively, we can add an extra dimension or two to the dp to indicate if we have ever taken a character from $x$ and from $y$. So we get $dp[i][j][c][fl_x][fl_y]$ with $fl_x$ and $fl_y$ being binary flags that tell if a character from $x$ and from $y$ was ever taken. That way we can only push the states with both flags set to true to the answer. Overall complexity: $O(|x| \cdot |y|)$.
[ "combinatorics", "dp", "math", "strings" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int main() { string s, t; cin >> s >> t; int n = s.size(), m = t.size(); vector<vector<vector<vector<int>>>> dp(n + 1, vector<vector<vector<int>>>(m + 1, vector<vector<int>>(2, vector<int>(4, 0)))); int ans = 0; forn(i, n + 1) forn(j, m + 1){ if (i < n) dp[i + 1][j][0][1] = add(dp[i + 1][j][0][1], 1); if (j < m) dp[i][j + 1][1][2] = add(dp[i][j + 1][1][2], 1); forn(mask, 4){ if (0 < i && i < n && s[i - 1] != s[i]) dp[i + 1][j][0][mask | 1] = add(dp[i + 1][j][0][mask | 1], dp[i][j][0][mask]); if (0 < j && i < n && t[j - 1] != s[i]) dp[i + 1][j][0][mask | 1] = add(dp[i + 1][j][0][mask | 1], dp[i][j][1][mask]); if (0 < i && j < m && s[i - 1] != t[j]) dp[i][j + 1][1][mask | 2] = add(dp[i][j + 1][1][mask | 2], dp[i][j][0][mask]); if (0 < j && j < m && t[j - 1] != t[j]) dp[i][j + 1][1][mask | 2] = add(dp[i][j + 1][1][mask | 2], dp[i][j][1][mask]); } ans = add(ans, dp[i][j][0][3]); ans = add(ans, dp[i][j][1][3]); } printf("%d\n", ans); return 0; }
1499
F
Diameter Cuts
You are given an integer $k$ and an undirected tree, consisting of $n$ vertices. The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree. You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to $k$. Two sets of edges are different if there is an edge such that it appears in only one of the sets. Count the number of valid sets of edges modulo $998\,244\,353$.
The task is obviously solved by dynamic programming, so our first reaction should be to start looking for meaningful states for it. Obviously, one of the states is the vertex which subtree we are processing. We can choose the root for the tree arbitrarily, let it be vertex $1$. What can be the other helpful state? Consider the method to find the diameter of the subtree of vertex $v$. The diameter can be one of the following paths: either the longest path that is completely in some subtree of $v$ or the concatenation of the longest paths that start in vertex $v$ and end in different subtrees. The diameter is the longest path. Thus, the diameter being less than or equal to $k$ means that all paths should have length less than or equal to $k$. If we can guarantee that no path that is completely in some subtree of $v$ have length greater than $k$, then we will only have to worry about not concatenating long paths from different subtrees. Phrase it the other way around: if we never concatenate the paths from the different subtrees in such a way that their total length is greater than $k$, then no diameter will be greater than $k$. Thus, we can attempt to have $dp[v][len]$ - the number of ways to cut some edges in the subtree of $v$ in such a way that there is no path of length greater than $k$ and the longest path starting at vertex $v$ has length $len$. Now for the transitions. For the simplicity, let vertex $v$ have exactly two children. It's not too hard to merge their $dp$'s. Iterate over the length $i$ of the first child, the length $j$ of the second child. If $(i+1)+(j+1) \le k$, then you can concatenate their longest paths and the longest path for $v$ will be of length $max(i,j)+1$. You can also cut either of the edges from $v$ to the first child or to the second child. The approach is good, however, it's not clear how to make it work on a larger number of children. Also, the complexity sounds pretty bad. Instead of merging children to each other, let's merge each child to the $dp$ of $v$ one by one. $dp[v][len]$ can store the current maximum length over all processed children. When processing a new child, you can choose to cut or not to cut the edge to it. So you can iterate over the current longest path from $v$ and the longest path from that child. So far, the only way to estimate the complexity is to say that each child has to merge its dp to the parent in $O(k^2)$, thus making the algorithm $O(nk^2)$. That's obviously too slow. The trick that makes the solution fast is to iterate not to $k$ but to the height of the subtree of $v$ and the subtree of a child. Surely, that is allowed, since the path just can't grow longer than that value. Consider the even worse option: not the height but the size of the subtree. It's easy to see that the size is always greater or equal than the height. Interpret the merge the following way: enumerate the vertices inside all the subtrees of the processed children and the vertices inside the subtree of the new child. Iterating up to the size of the subtree is the same number of moves as going over the vertices in it. The merge will go over all the pairs of vertices such that the first vertex of the pair is in the first set and the second vertex is in the second set. Thus, each pair of vertices of the tree will be processed exactly once (in lca of these vertices). There are $O(n^2)$ such pairs, thus, such $dp$'s work in $O(n^2)$. Overall complexity: $O(n^2)$.
[ "combinatorics", "dfs and similar", "dp", "trees" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int k; vector<vector<int>> g; vector<vector<int>> dp; int dfs(int v, int p = -1){ dp[v][0] = 1; int h = 0; for (int u : g[v]) if (u != p){ int nh = dfs(u, v); vector<int> tmp(max(h, nh + 1) + 1); forn(i, h + 1) forn(j, nh + 1){ if (i + j + 1 <= k) tmp[max(i, j + 1)] = add(tmp[max(i, j + 1)], mul(dp[v][i], dp[u][j])); if (i <= k && j <= k) tmp[i] = add(tmp[i], mul(dp[v][i], dp[u][j])); } h = max(h, nh + 1); forn(i, h + 1){ dp[v][i] = tmp[i]; } } return h; } int main() { int n; scanf("%d%d", &n, &k); g.resize(n); dp.resize(n, vector<int>(n, 0)); forn(i, n - 1){ int v, u; scanf("%d%d", &v, &u); --v, --u; g[v].push_back(u); g[u].push_back(v); } dfs(0); int ans = 0; forn(i, k + 1) ans = add(ans, dp[0][i]); printf("%d\n", ans); return 0; }
1499
G
Graph Coloring
You are given a bipartite graph consisting of $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges, numbered from $1$ to $m$. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: $\sum \limits_{v \in V} |r(v) - b(v)|$, where $V$ is the set of vertices of the graph, $r(v)$ is the number of red edges incident to $v$, and $b(v)$ is the number of blue edges incident to $v$. Sounds classical and easy, right? Well, you have to process $q$ queries of the following format: - $1$ $v_1$ $v_2$ — add a new edge connecting the vertex $v_1$ of the first part with the vertex $v_2$ of the second part. This edge gets a new index as follows: the first added edge gets the index $m + 1$, the second — $m + 2$, and so on. After adding the edge, you have to print the hash of the current optimal coloring (if there are multiple optimal colorings, print the hash of any of them). \textbf{Actually, this hash won't be verified, you may print any number as the answer to this query, but you may be asked to produce the coloring having this hash}; - $2$ — print the optimal coloring of the graph with the same hash you printed while processing the previous query. The query of this type will only be asked after a query of type $1$, and there will be at most $10$ queries of this type. If there are multiple optimal colorings corresponding to this hash, print any of them. Note that if an edge was red or blue in some coloring, it may change its color in next colorings. The hash of the coloring is calculated as follows: let $R$ be the set of indices of red edges, then the hash is $(\sum \limits_{i \in R} 2^i) \bmod 998244353$. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
Let's split all edges of the graph into several paths and cycles (each edge will belong to exactly one path or cycle). Each path and each cycle will be colored in an alternating way: the first edge will be red, the second - blue, the third - red, and so on (or vice versa). Since the graph is bipartite, each cycle can be colored in an alternating way. The main idea of the solution is to add the edges one by one, maintain the structure of cycles and paths, and make sure that for each vertex, at most one path starts/ends in it. If we are able to maintain this invariant, then the value of $|r(v) - b(v)|$ for every vertex will be minimum possible - each cycle going through a vertex covers an even number of edges incident to it (half of them will be red, half of them will be blue); so, if the degree of a vertex is odd, one path will have this vertex as an endpoint, and $|r(v) - b(v)| = 1$; otherwise, it won't be an endpoint of any path, so $|r(v) - b(v)| = 0$. Okay, how do we maintain this structure? Let's add edges one by one (even the original edges of the graph) and rebuild the structure in online mode. For each vertex, we will maintain the indices of the paths that have this vertex as an endpoint. If some vertex has $2$ or more paths as its endpoints, we can choose two of them and link them together. Whenever we add an edge from $x$ to $y$, we just create a new path and check if we can link together some paths that have $x$ or $y$ as their endpoints. How do we link the paths together? If we try to link a path with itself, it means that we try to close a cycle - and when we do it, we just forget about the resulting cycle, its structure won't change in future queries. When we link a path with some other path, we might need to reverse and/or repaint the paths before merging them into one. There are (at least) two possible data structures we can use to do this: either an implicit-key treap that supports reversing and repainting; or a deque with small-to-large merging: whenever we try to link two paths together, we repaint and/or reverse the smaller one. Both of those methods give a solution in $O((m + q) \log(m + q))$ or $O((m + q) \log^2(m + q))$, depending on your implementation. The model solution uses deques and small-to-large merging.
[ "data structures", "graphs", "interactive" ]
3,100
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 1000043; 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 binpow(int x, int y) { int z = 1; while(y > 0) { if(y % 2 == 1) z = mul(z, x); x = mul(x, x); y /= 2; } return z; } int global_hash = 0; void reverse(deque<pair<int, int>>& d) { stack<pair<int, int>> s; while(!d.empty()) { s.push(d.back()); d.pop_back(); } while(!s.empty()) { d.push_front(s.top()); s.pop(); } } void safe_push_front(deque<pair<int, int>>& d, int c, int& res) { int z = d.front().first ^ 1; res = add(res, mul(binpow(2, c), z)); d.push_front(make_pair(z, c)); } void safe_push_back(deque<pair<int, int>>& d, int c, int& res) { int z = d.back().first ^ 1; res = add(res, mul(binpow(2, c), z)); d.push_back(make_pair(z, c)); } deque<pair<int, int>> ds[N]; struct path { int s; int t; int d; int c; path() {}; path(int s, int t, int d, int c) : s(s), t(t), d(d), c(c) {}; void push_front(int i) { safe_push_front(ds[d], i, c); } void push_back(int i) { safe_push_back(ds[d], i, c); } void pop_front() { ds[d].pop_front(); } void pop_back() { ds[d].pop_back(); } int front() { return ds[d].front().second; } int back() { return ds[d].back().second; } void reverse() { ::reverse(ds[d]); swap(s, t); } int size() { return ds[d].size(); } }; path link_to_left(path x, path y) { path z = x; while(y.size() > 0) { z.push_back(y.front()); y.pop_front(); } z.t = y.t; return z; } path link_to_right(path x, path y) { path z = y; while(x.size() > 0) { z.push_front(x.back()); x.pop_back(); } z.s = x.s; return z; } int cur = 0; path make(int x, int y, int i) { int cost = i; ds[cur].push_back(make_pair(0, cost)); return path(x, y, cur++, 0); } set<int> paths; vector<int> paths_v[N]; path ps[N]; path merge(path x, path y, int v) { if(x.size() > y.size()) swap(x, y); if(y.s == v) { if(x.t != v) x.reverse(); return link_to_right(x, y); } else { if(x.s != v) x.reverse(); return link_to_left(y, x); } } int cur2 = 0; void modify(vector<int>& v, int x, int y) { for(int i = 0; i < v.size(); i++) if(v[i] == x) v[i] = y; } void reassign(path p, int x, int y) { modify(paths_v[p.s], x, y); modify(paths_v[p.t], x, y); } void merge_paths(int x, int y, int v) { if(x == y) { } else { global_hash = sub(global_hash, ps[x].c); global_hash = sub(global_hash, ps[y].c); ps[cur2++] = merge(ps[x], ps[y], v); paths.erase(x); paths.erase(y); paths.insert(cur2 - 1); reassign(ps[x], x, cur2 - 1); reassign(ps[y], y, cur2 - 1); global_hash = add(global_hash, ps[cur2 - 1].c); } } void relax(int v) { while(paths_v[v].size() >= 2) { int x = paths_v[v].back(); paths_v[v].pop_back(); int y = paths_v[v].back(); paths_v[v].pop_back(); merge_paths(x, y, v); } } void add_edge(int x, int y, int i) { //cerr << x << " " << y << " " << i << endl; int c = cur2; ps[cur2++] = make(x, y, i); paths_v[x].push_back(c); paths_v[y].push_back(c); paths.insert(c); relax(x); relax(y); } void print_coloring() { vector<int> ans; for(auto x : paths) { for(auto y : ds[ps[x].d]) { if(y.first == 1) ans.push_back(y.second); } } printf("%d", int(ans.size())); for(auto x : ans) printf(" %d", x); puts(""); fflush(stdout); } int e = 0; void process_query() { int t; scanf("%d", &t); if(t == 1) { int x, y; scanf("%d %d", &x, &y); y += 200001; add_edge(x, y, ++e); printf("%d\n", global_hash); fflush(stdout); } else print_coloring(); } void print_info() { cerr << "Paths\n"; for(auto x : paths) cerr << x << " start: " << ps[x].s << " " << " end: " << ps[x].t << endl; cerr << "Vertices\n"; for(int i = 0; i < N; i++) if(!paths_v[i].empty()) { cerr << i << ": "; for(auto x : paths_v[i]) cerr << x << " "; cerr << endl; } } int main() { int n1, n2, m; scanf("%d %d %d", &n1, &n2, &m); for(int i = 0; i < m; i++) { int x, y; scanf("%d %d", &x, &y); y += 200001; add_edge(x, y, ++e); } int q; scanf("%d", &q); for(int i = 0; i < q; i++) { //print_info(); process_query(); } }
1500
A
Going Home
It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $a$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four \textbf{different} indices $x, y, z, w$ such that $a_x + a_y = a_z + a_w$. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?
Let's prove that if there're at least four different pairs indices with the common sum ($a_{x_1} + a_{y_1} = a_{x_2} + a_{y_2} = \ldots = a_{x_4} + a_{y_4}$), then there necessarily will be two pairs such that all four indices in them are unique. Let's analyze some cases: There're four pairs of the form $(x, y_1), (x, y_2), (x, y_3), (x, y_4)$ with sum $S$. Then $a_x + a_{y_1} = a_x + a_{y_2} = a_x + a_{y_3} = a_x + a_{y_4} = S$ from which we can conclude that $a_{y_1} = a_{y_2} = a_{y_3} = a_{y_4}$, and it means that pairs $(y_1, y_2)$ and $(y_3, y_4)$ are suitable as answer. There're three pairs of the form $(x, y_1), (x, y_2), (x, y_3)$ and the fourth pair doesn't contain index $x$. Then whatever the fourth pair $(z, w)$ is, it necessarily doesn't contain index $x$ and at least one of indices $y_1, y_2, y_3$ which means we can take as answer pairs $(z, w)$ and one of three that contain $x$. Other cases are analyzed in the same way. To make sure that answer always exists among such four pairs, we can imagine graph, where vertices are indices, and there is an edge between two vertices if the corresponding pair of indices has sum $S$. If such a graph has at least four edges and the degree of all vertices is at most two (we excluded the larger degrees by examining the previous cases), then there will always be two edges with disjoint ends. How to find answer using this? Let's launch simple $\mathcal{O}(n^2)$ bruteforce which for every sum will save all found pairs with such sum, and for each pair check if there's another already found pair with the same sum and such indices that all four indices in these two pairs are unique. Let's notice it works in $\mathcal{O}(min(n^2, n + C)$, because once for some sum we find the fourth pair, we can immediately print the answer. And if the answer is "NO", then we've done no more than $\mathcal{O}(C)$ iterations of bruteforce.
[ "brute force", "hashing", "implementation", "math" ]
1,800
null
1500
B
Two chandeliers
Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers. Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the $k$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers. Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.
A formal statement of the problem: there are two sequences of distinct integers, whose are infinitely cycled. You need to find prefix of minimal length which contains exactly $k$ positions $i$ such that $a_i \neq b_i$. Let's notice that we can use binary search. So we need to count number of positions $i$ such that $a_i \neq b_i$ on prefix of length $x$. Because all integers in $a_i$ are distinct (and also in $b_i$), we need to calculate number of non-negative solutions: $\begin{cases} pos \equiv x \pmod{n} \\ pos \equiv y \pmod{m}\end{cases}$ If $n$ and $m$ are coprime, the value can be calculated with Chinese remainder theorem. Solution's complexity will be $O((n + m) \cdot \log(n + m) \cdot \log(k \cdot (n + m))$. If $n$ and $m$ are not coprime, participant can make transition $(n, m) \to (\frac{n}{gcd(n, m)}, \frac{m}{gcd(n, m)})$, solve new equations, and then make reverse transition. After that, you need to optimize this solution. There are many ways to do this, for example, you can precalculate solutions of all equations. And complexity becomes $O((n + m) \cdot (\log(k) + \log(n + m)))$
[ "binary search", "brute force", "chinese remainder theorem", "math", "number theory" ]
2,200
null
1500
C
Matrix Sorting
You are given two tables $A$ and $B$ of size $n \times m$. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table $A$ opened right now. He wants to perform zero of more sortings by column to transform this table to table $B$. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you \textbf{do not need} to minimize the number of sortings.
Let's first learn how to solve with O ($n \cdot m^2$). Note that each column can be sorted no more than once. Now, let's note that if we could turn matrix A into matrix B, then B has a sorted column. Idea - we will choose the rows that we will sort from the end. To do this, we can support string equivalence classes. Where and why? If two rows are in the same class, then the columns that we applied had the same values. Then, we need to find a column that does not break the sequence between the rows inside each of the classes. Let's iterate through such a column every time. We don't care if we apply someone extra - because of the condition of the possibility of application, it will definitely not spoil. Then just apply the column if we could. Each time, the number of equivalence classes does not decrease, so the number of columns that can be applied does not decrease. If it was not possible to sort after all the applications, it means that some of the classes could not be split correctly, which means that it is impossible to get matrix B from matrix A. Let's learn how to solve it faster than in a cube. Let's not store equivalence classes explicitly. To do this, note that in the final state of B, the equivalence classes are sub-arrays! Then it is enough for us to store for each pair of adjacent rows whether we were able to separate them (swap the lower and upper places) - let's call it $cut$. Also, for each column, we will store the number of still unresolved inversions in it, call it $cnt$. Initially, - is just the number of inversions in the column. Next, it will be the same number of inversions, but only within the classes. How does this solution differ from a cube? We are able to quickly find which column can be applied - this is the column $j$ for which $cnt[j] = 0$. Then we just need to learn how to update the cnt. Let's start a queue (we can say that this is bfs, but in fact we do not use anything other than a queue from bfs), to which we will add only columns $j$ in which $cnt[j] = 0$, apply sorting by column, update cnt and add new columns that have $cnt=0$. $cut$will help us with this. Let's, if we managed to swap the columns (that is, in the current column $v$, $b[i][v] < b[i - 1][v]$), set $cut[i] = 1$ and update all the values of $cnt$ through this row. It is clear that it does not make sense to split rows twice. Since we will apply each column at most once, and the pairs of adjacent rows are $O(n)$, the time complexity is $O (n \cdot m)$. Do not forget that it is not necessary to divide into exactly $n$ equivalence classes, because a smaller number may be enough. So in the end, check transformations(not difficult, but need to be careful). There is also a solution with time complexity $O(nm log)$, but I think, it is more difficult both in terms of understanding and implementation.
[ "bitmasks", "brute force", "constructive algorithms", "greedy", "two pointers" ]
2,600
null
1500
D
Tiles for Bathroom
Kostya is extremely busy: he is renovating his house! He needs to hand wallpaper, assemble furniture throw away trash. Kostya is buying tiles for bathroom today. He is standing in front of a large square stand with tiles in a shop. The stand is a square of $n \times n$ cells, each cell of which contains a small tile with color $c_{i,\,j}$. The shop sells tiles in packs: more specifically, you can only buy a subsquare of the initial square. A subsquare is any square part of the stand, i. e. any set $S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i < i_0 + k, j_0 \le j < j_0 + k\}$ with $1 \le i_0, j_0 \le n - k + 1$. Kostya still does not know how many tiles he needs, so he considers the subsquares of all possible sizes. He doesn't want his bathroom to be too colorful. Help Kostya to count for each $k \le n$ the number of subsquares of size $k \times k$ that have at most $q$ different colors of tiles. Two subsquares are considered different if their location on the stand is different.
Let's denote $ans_{i,\,j}$ as max "good" subsquare side size with left top angle at $(i,\,j)$ cell. It's obvious that every subsquare with side less than $ans_{i,\,j}$ is "good" too. So we need to find $ans_{i,\,j}$ and then print answer for k-size side as $\displaystyle \sum_{x=k}^{n} |\{(i,\,j)\ |\ ans_{i,\,j} = k\}$. This value can be found with partial sums on count array of $ans_{i,\,j}$. Now we need to calculate $ans_{i,\,j}$. Let's notice that $ans_{i,\,j+1} \ge ans_{i,\,j} - 1$, because $(i, j + 1)$-th square is inside of $(i, j)$ square if it's side is longer than 1. So, we can use amortized algorithm of sequential increase square's side. Every time when we can increase $ans_{i,\,j}$ we will do it, then we will go to calculating $ans_{i,\,j+1}$. Using linear algorithm to check if new square's size is "good", we will get $O(n^3)$ solution, which is not effective enough, but can be optimized. Now let's use small constraints for $q$. For each $(i,\,j)$ cell we will precalc array $colors_{i,\,j}$, which will have $(q + 1)$ nearest colors in line $(i',\,j), i' \ge i$. For each color, we will keep it's earliest occurrence It can be calculated in $O(n^2 q)$, because $colors_{i,\,j} = colors_{i,\,j + 1} \cup c_{i,\,j}$. If $c_{i,\,j}$ exists in $colors_{i,\,j}$, we must change earliest occurrence. If it isn't, we should delete the most far color, then insert the current one. All values can be keeped with increasing left occurrence in $O(q)$ for each cell. Last step - we can merge $colors_{i,\,j},\ \ldots,\ colors_{i + m - 1,\,j}$ in $O(mq)$ - it will be the array of $q + 1$ values corresponding for earliest colors in line of width $m$. Merging two lines is almost like merge of two sorted arrays - it is used to find $q + 1$ minimal left occurrences. Maximal "good" width can be found as left occurrence of $(q+1)$-th elementh minus $j$. Now we need to unite some rows in a structure and merge lines for current square, then erase first row and repeat the process. The structure can be realized as queue on two stacks, each of whose is keeping merge value of all lines in itself. The algorithm is almost like queue with minimal value (https://cp-algorithms.com/data_structures/stack_queue_modification.html). That's how we get solution with complexity $O(n^2q)$.
[ "data structures", "sortings", "two pointers" ]
2,900
null
1500
E
Subset Trick
Vanya invented an interesting trick with a set of integers. Let an illusionist have a set of positive integers $S$. He names a positive integer $x$. Then an audience volunteer must choose some subset (possibly, empty) of $S$ without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed $x$. The sum of elements of an empty subset is considered to be $0$. Vanya wants to prepare the trick for a public performance. He prepared some set of \textbf{distinct} positive integers $S$. Vasya wants the trick to be successful. He calls a positive number $x$ unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose. Vanya wants to count the number of unsuitable integers for the chosen set $S$. Vanya plans to try different sets $S$. He wants you to write a program that finds the number of unsuitable integers for the initial set $S$, and after each change to the set $S$. Vanya will make $q$ changes to the set, and each change is one of the following two types: - add a new integer $a$ to the set $S$, or - remove some integer $a$ from the set $S$.
Let $S = \{a_1, a_2, \ldots, a_n\}$, where $a_1 < a_2 < \ldots < a_n$. Let's calculate the number of good numbers from $0$ to $sum(X) - 1$. To get the answer to our problem we should subtract this value from $sum(S)$. Let's suppose that $0 \leq x < sum(X)$ is good. It is easy to see that it is equivalent to $a_{n - k + 1} + \ldots + a_{n} \leq x < a_{1} + \ldots + a_{k+1}$ for some $0 \leq k < n$. So to calculate the required number of good numbers we should find the length of the union of intervals $[a_{n - k + 1} + \ldots + a_{n}, a_{1} + \ldots + a_{k+1})$ for all $0 \leq k < n$. We can note two things: some of these intervals are empty all non-empty intervals does not intersect with each other So the number we want to find is just $\sum\limits_{k=0}^{n-1} \max{(a_{1} + \ldots + a_{k+1} - a_{n - k + 1} - \ldots - a_{n}, 0)}$. Let's call $f(k) = a_{1} + \ldots + a_{k+1} - a_{n - k + 1} - \ldots - a_{n}$. Let's note two simply things: $f(k) = f(n - 1 - k)$ $f(x) \geq f(y)$ if $x \leq y \leq \frac{n-1}{2}$ Let's use them. First of all let's find $\sum\limits_{k=0}^{\frac{n-1}{2}} \max{(f(k), 0)}$. We can simply calculate the sum we need from it because we should just multiply this sum by $2$ and possibly subtract the number from the middle (if $n$ is odd). Let's note that in the sum $\sum\limits_{k=0}^{\frac{n-1}{2}} \max{(f(k), 0)}$ some first summands are $> 0$, others are equal to $0$ (because $0$ will be bigger in the maximum). Let's find the minimal $l \leq \frac{n-1}{2}$, such that $f(l) \leq 0$ using binary search. After that we should calculate $\sum\limits_{k=0}^{l-1} f(k) = \sum\limits_{k=0}^{l-1} (a_{1} + \ldots + a_{k+1} - a_{n - k + 1} - \ldots - a_{n}) = \sum\limits_{i=0}^{l} a_i (l - i) - \sum\limits_{i=n-l+1}^{n} a_i (i + l - n)$. So what values we should be able to calculate to solve the problem? The sum of numbers on prefix $\sum\limits_{i=0}^{k} a_i$. Using two queries of this type we can calculate $f(k)$. The sum of numbers multiplied by index on prefix $\sum\limits_{i=0}^{k} a_i i$. We can calculate the final answer using this query. To answer these queries effectively let's use the segment tree. Initially let's find all numbers that will be in $S$ in some moment (we can do it because we have the list of all queries). We will make a segment tree on this array, where we will write $0$, if there is no such number currently in $S$ and $1$, otherwise. For each segment of these segment tree we will store $3$ values: the number of numbers from this segment, that lie in the current $S$ the sum of numbers from this segment, that lie in the current $S$ the sum of numbers multiplied by index from this segment, that lie in the current $S$ These values can be easily recalculated when an update in the segment tree happens. To calculate two sums required for us we need to make the descent in the segment tree summing the segments on the prefix, where the number of numbers that lie in the current $S$ is equal to $k$. In total, we get the $O((n+q) \log^2{(n+q)})$ solution, because we make the binary search and use queries to the segment tree inside it.
[ "binary search", "data structures" ]
3,300
null
1500
F
Cupboards Jumps
In the house where Krosh used to live, he had $n$ cupboards standing in a line, the $i$-th cupboard had the height of $h_i$. Krosh moved recently, but he wasn't able to move the cupboards with him. Now he wants to buy $n$ new cupboards so that they look as similar to old ones as possible. Krosh does not remember the exact heights of the cupboards, but for every three consecutive cupboards he remembers the height difference between the tallest and the shortest of them. In other words, if the cupboards' heights were $h_1, h_2, \ldots, h_n$, then Krosh remembers the values $w_i = \max(h_{i}, h_{i + 1}, h_{i + 2}) - \min(h_{i}, h_{i + 1}, h_{i + 2})$ for all $1 \leq i \leq n - 2$. Krosh wants to buy such $n$ cupboards that all the values $w_i$ remain the same. Help him determine the required cupboards' heights, or determine that he remembers something incorrectly and there is no suitable sequence of heights.
$-$ Note 1 We can change cupboards' heights with differences between following ones: $d_i = h_{i + 1} - h_{i}$. How to get $w$ using $d$? $w_i = \max(\left|{d_i}\right|, \left|{d_{i + 1}}\right|, \left|{d_i + d_{i + 1}}\right|)$ $\quad$ $-$ $O(n C)$ $dp[i][dif]$ - can we choose $i$ differences, with the last equal to $dif$ Can be updated with $O(1)$ checks $\quad$ $-$ Note 2 If we can get $dif$ difference, then $-dif$ too, because we can invert all differences on prefix and save all conditions. So keep in mind just $dif \in [0, C]$ $\quad$ $-$ $O(n^2)$ Let's keep values on each layer we can get as segments. We show that there will be O(n) of them for each layer. Segment $[0; w_i]$ is full able if previous layer has value $w_i$ Each segment $[l, r]$ goes to $[\max(w_i - r, 0), w_i - l]$ If some segment had $x: x \leq w_i$, then we should add: $[w_i, w_i]$ Restoring the answer: since we keep all segments for each layer, we can check that previous one contains: $w_i$ $w_i - dif$ anything $\leq w_i$, if $dif = w_i$ $-$ $O(n)$ Segments don't change much. Each layer change is: inversion + shift + truncation with zero ($[l, r] \to [\max(w_i - r, 0), w_i - l]$) check for a corner value ($w_i \to [0, w_i]$) add corner value ($x \leq w_i \to [w_i, w_i]$) After recalculating value of $cf$ and $sh$: let's trunc segments from corners to keep just values in $[0, w_i]$ and add $[w_i, w_i]$(converted) if we need to. Number of truncation will be $O(n)$. Restoring: If $w_i$ was at previous layer - keep it and use If $dif = w_i$, use minimum value from previous layer Otherwise we should definitely use $w_i - dif$
[ "dp" ]
3,500
null
1501
A
Alexey and Train
Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should! Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $0$. Also, let's say that the train will visit $n$ stations numbered from $1$ to $n$ along its way, and that Alexey destination is the station $n$. Alexey learned from the train schedule $n$ integer pairs $(a_i, b_i)$ where $a_i$ is the expected time of train's arrival at the $i$-th station and $b_i$ is the expected time of departure. Also, using all information he has, Alexey was able to calculate $n$ integers $tm_1, tm_2, \dots, tm_n$ where $tm_i$ is the extra time the train need to travel from the station $i - 1$ to the station $i$. Formally, the train needs exactly $a_i - b_{i-1} + tm_i$ time to travel from station $i - 1$ to station $i$ (if $i = 1$ then $b_0$ is the moment the train leave the terminal, and it's equal to $0$). The train leaves the station $i$, if both conditions are met: - it's on the station for at least $\left\lceil \frac{b_i - a_i}{2} \right\rceil$ units of time (division with ceiling); - current time $\ge b_i$. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of \textbf{arrival} at the station $n$.
The solution of this task is to basically implement what was written in the statement. Let $dep_i$ be the moment of train departure from the station $i$ ($dep_0 = 0$ initially). Then train arrives at the current station $i$ at moment $ar_i = dep_{i - 1} + (a_i - b_{i - 1}) + tm_i$ and departure at moment $dep_i = \max(b_i, ar_i + \frac{b_i - a_i + 1}{2})$. The answer is $ar_n$.
[ "implementation" ]
800
null
1501
B
Napoleon Cake
This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead. To bake a Napoleon cake, one has to bake $n$ dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps $n$ times: - place a new cake layer on the top of the stack; - after the $i$-th layer is placed, pour $a_i$ units of cream on top of the stack. When $x$ units of cream are poured on the top of the stack, top $x$ layers of the cake get drenched in the cream. If there are less than $x$ layers, all layers get drenched and the rest of the cream is wasted. If $x = 0$, no layer gets drenched. \begin{center} {\small The picture represents the first test case of the example.} \end{center} Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.
The $i$-th layer is drenched in cream if there is such $j \ge i$ that $j - a_j < i$. Then we can calculate answers for all layers $i$ in reverse order (from $n$ to $1$) and maintain minimum over all values $j - a_j$ as some variable $mn$. As a result, when we move from $i + 1$ to $i$, we update $mn = \min(mn, i - a_i)$ and then check that $mn < i$.
[ "dp", "implementation", "sortings" ]
900
null
1503
A
Balance the Bits
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not. You are given a binary string $s$ of length $n$. Construct two balanced bracket sequences $a$ and $b$ of length $n$ such that for all $1\le i\le n$: - if $s_i=1$, then $a_i=b_i$ - if $s_i=0$, then $a_i\ne b_i$ If it is impossible, you should report about it.
Any balanced bracket sequence must begin with '(' and end with ')'. Therefore, $a$ and $b$ must agree in the first and last positions, so we require $s_1=s_n=1$ or a solution doesn't exist. The total number of open brackets in $a$ and $b$ must be $n$, which is even. Each $1$ bit in $s$ creates an even number of open brackets and each $0$ bit creates an odd number of open brackets. Therefore, there must be an even number of $0$ bits, or a solution doesn't exist. Note that the number of $1$ bits also must be even. Assuming these conditions hold, let's construct a solution. Suppose there are $k$ positions where $s_i=1$. We will make the first $\frac k2$ positions open in both $a$ and $b$, and we will make the last $\frac k2$ positions closed in both $a$ and $b$. Then, the $0$ bits in $s$ will alternate between which string gets the open bracket.
[ "constructive algorithms", "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve() { int n; string s; cin >> n >> s; int cnt = 0; for(int i = 0; i < n; i++) { cnt += (s[i] == '1'); } if(cnt % 2 == 1 || s[0] == '0' || s.back() == '0') { cout << "NO\n"; return; } string a, b; int k = 0; bool flip = false; for(int i = 0; i < n; i++) { if(s[i] == '1') { a.push_back(2 * k < cnt ? '(' : ')'); b.push_back(a.back()); k++; }else { a.push_back(flip ? '(' : ')'); b.push_back(flip ? ')' : '('); flip = !flip; } } cout << "YES\n" << a << '\n' << b << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); int te; cin >> te; while(te--) solve(); }
1503
B
3-Coloring
\textbf{This is an interactive problem.} Alice and Bob are playing a game. There is $n\times n$ grid, initially empty. We refer to the cell in row $i$ and column $j$ by $(i, j)$ for $1\le i, j\le n$. There is an infinite supply of tokens that come in $3$ colors labelled $1$, $2$, and $3$. The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it $a$. Then, Bob chooses a color $b\ne a$, chooses an empty cell, and places a token of color $b$ on that cell. We say that there is a \textbf{conflict} if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge. If at any moment there is a conflict, Alice wins. Otherwise, if $n^2$ turns are completed (so that the grid becomes full) without any conflicts, Bob wins. We have a proof that Bob has a winning strategy. Play the game as Bob and win. The interactor is \textbf{adaptive}. That is, Alice's color choices can depend on Bob's previous moves.
Imagine the grid is colored like a checkerboard with black and white squares. Then Bob's strategy is to put tokens $1$ on white squares and tokens $2$ on black squares as long as he is able. If he is unable, this means all squares of one color are filled, and he can start placing tokens $3$ without making an invalid coloring. More specifically, this is his strategy: If Alice chooses $1$: If a black square is free, place a $2$ there. Otherwise, place a $3$ on a white cell. If a black square is free, place a $2$ there. Otherwise, place a $3$ on a white cell. If Alice chooses $2$: If a white square is free, place a $1$ there. Otherwise, place a $3$ on a black cell. If a white square is free, place a $1$ there. Otherwise, place a $3$ on a black cell. If Alice chooses $3$: If a white square is free, place a $1$ there. Otherwise, place a $2$ on a black cell. If a white square is free, place a $1$ there. Otherwise, place a $2$ on a black cell.
[ "constructive algorithms", "games", "interactive" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<pair<int, int>> ve[2]; #define BLACK 0 #define WHITE 1 // color the cells like a checkerboard // ve[COLOR] = {list of unfilled cells of that color} for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { ve[(i + j) % 2].push_back({i, j}); } } for(int t = 1; t <= n * n; t++) { int a, b, i, j, col; cin >> a; // choose an available checkerboard color and a token color for it if(a == 1) { if(!ve[BLACK].empty()) { col = BLACK; b = 2; }else { col = WHITE; b = 3; } }else if(a == 2) { if(!ve[WHITE].empty()) { col = WHITE; b = 1; }else { col = BLACK; b = 3; } }else { // a == 3 if(!ve[WHITE].empty()) { col = WHITE; b = 1; }else { col = BLACK; b = 2; } } tie(i, j) = ve[col].back(); ve[col].pop_back(); cout << b << ' ' << i << ' ' << j << endl; } }
1503
C
Travelling Salesman Problem
There are $n$ cities numbered from $1$ to $n$, and city $i$ has beauty $a_i$. A salesman wants to start at city $1$, visit every city exactly once, and return to city $1$. For all $i\ne j$, a flight from city $i$ to city $j$ costs $\max(c_i,a_j-a_i)$ dollars, where $c_i$ is the price floor enforced by city $i$. Note that there is no absolute value. Find the minimum total cost for the salesman to complete his trip.
Let's reindex the cities so they are in increasing order of beauty. Note that it doesn't matter which city we call the start: the trip will be a cycle visiting every city exactly once. Let's rewrite the cost of a flight $i\to j$ as $\max(c_i, a_j-a_i)=c_i+\max(0, a_j-a_i-c_i).$ Since we always need to leave each city exactly once, we can ignore the $c_i$ term from all flights and only try to minimize the sum of $\max(0,a_j-a_i-c_i).$ Note that a flight to a city of smaller beauty is always free in the adjusted cost. So all we need is a path from $a_1$ to $a_n$, and the rest of the trip can be done for free. Also, any valid trip will contain a path from $a_1$ to $a_n$, so the shortest path is optimal. Solution 1 All we have to do is encode the graph without storing all edges explicitly, and we can simply run Dijkstra's algorithm to find the shortest path. Add the following edges: $a_i\to a_{i-1}$ with weight $0$. $i\to j$ with weight $0$, where $j$ is the largest index with $a_j-a_i-c_i\le 0$. The index $j$ can be found with binary search. $i\to j+1$ with weight $\max(0, a_{j+1}-a_i-c_i)$ where $j$ is the same as before. Every edge in this new graph corresponds to an edge in the original graph, and every edge in the original graph corresponds to a path in the new graph with at most the same cost. So the distance from $a_1$ to $a_n$ is preserved. Solution 2 A simpler solution is to compute for all $i>1$, the minimum possible cost of the first trip reaching $a_i$ or larger. It's easy to see that any path must have at least this cost, and we can construct a path of this cost since moving to smaller $a_i$ is free. It corresponds to the following summation. $\sum_{i=2}^n \max(0, a_i-\max_{j<i}(a_j+c_j))$ Complexity is $O(n\log n)$.
[ "binary search", "data structures", "dp", "greedy", "shortest paths", "sortings", "two pointers" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<pair<long long, long long>> ve; long long ans = 0; for(int i = 0; i < n; i++) { long long a, c; cin >> a >> c; ve.push_back({a, c}); ans += c; } sort(ve.begin(), ve.end()); long long mx = ve[0].first + ve[0].second; for(int i = 1; i < n; i++) { ans += max(0LL, ve[i].first - mx); mx = max(mx, ve[i].first + ve[i].second); } cout << ans << '\n'; }
1503
D
Flip the Cards
There is a deck of $n$ cards. The $i$-th card has a number $a_i$ on the front and a number $b_i$ on the back. Every integer between $1$ and $2n$ appears exactly once on the cards. A deck is called sorted if the front values are in \textbf{increasing} order and the back values are in \textbf{decreasing} order. That is, if $a_i< a_{i+1}$ and $b_i> b_{i+1}$ for all $1\le i<n$. To flip a card $i$ means swapping the values of $a_i$ and $b_i$. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Suppose there is a sorted deck where the $i$-th card has $c_i$ on the front and $d_i$ on the back. That is, it looks like this: $c_1< c_2< \cdots< c_n\\ d_1> d_2> \cdots> d_n$ The values $1,\ldots, n$ must appear in some prefix of $c_i$ and some suffix of $d_i$. That is, they must all appear on distinct cards. So, if two values between $1$ and $n$ appear on the same card, we should report there is no solution. Now, we know that every card in the input has a value in $[1,n]$ and a value in $[n+1,2n]$. Let $f(k)$ denote the number matched with the value $k$. Let's split the cards into two sets. Set $A$ will be the cards that will end with the smaller number on the front, and $B$ is the set of cards ending with the smaller number on the back. In each set, as the smaller numbers increase, the larger numbers decrease. Therefore, it must be possible to decompose $[f(1),\ldots,f(n)]$ into two decreasing subsequences, or there is no solution. To decompose an array into two decreasing subsequences, there is a standard greedy approach. Also, note that any decomposition of $[f(1),\ldots,f(n)]$ into two decreasing sequences corresponds to a solution. In fact, we can put all the cards of one subsequence in $A$ and the rest in $B$, and it will create a sorted deck. But how can we find the decomposition that corresponds to the minimum number of card flips? For every index $i$ such that $\min\limits_{j\le i} f(j)>\max\limits_{j>i}f(j)$, let's add a divider between $i$ and $i+1$. This splits the array $[f(1),\ldots, f(n)]$ into several segments. We can independently choose how to decompose each segment into two subsequences, and combining them is guaranteed to be a valid decomposition for the entire array. Also, there is a unique way to decompose each segment: the only choice is in which one we call the first subsequence. And so, we can independently choose for each segment the choice that requires the smallest number of flips. Complexity is $O(n)$.
[ "2-sat", "constructive algorithms", "data structures", "greedy", "sortings", "two pointers" ]
2,600
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> ve(n + 1), c(n + 1), suffmax(n + 2), seq0, seq1; bool flag = true; for(int i = 0; i < n; i++) { int a, b; cin >> a >> b; int cost = 0; if(a > b) { cost = 1; swap(a, b); } if(a <= n) { ve[a] = b; c[a] = cost; }else flag = false; } if(!flag) { cout << -1 << '\n'; return; } suffmax[n + 1] = -1; for(int i = n; i >= 1; i--) { suffmax[i] = max(suffmax[i + 1], ve[i]); } int prefmin = INT_MAX; int cost0 = 0, cost1 = 0, ans = 0; for(int i = 1; i <= n; i++) { prefmin = min(prefmin, ve[i]); if(seq0.empty() || ve[seq0.back()] > ve[i]) { seq0.push_back(i); cost0 += c[i]; }else if(seq1.empty() || ve[seq1.back()] > ve[i]) { seq1.push_back(i); cost1 += c[i]; }else { cout << -1 << '\n'; return; } if(prefmin > suffmax[i + 1]) { int s0 = (int) seq0.size(), s1 = (int) seq1.size(); ans += min(cost0 + s1 - cost1, s0 - cost0 + cost1); cost0 = cost1 = 0; seq0.clear(); seq1.clear(); } } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); solve(); }
1503
E
2-Coloring
There is a grid with $n$ rows and $m$ columns. Every cell of the grid should be colored either blue or yellow. A coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells. In other words, every row must have at least one blue cell, and all blue cells in a row must be consecutive. Similarly, every column must have at least one yellow cell, and all yellow cells in a column must be consecutive. \begin{center} An example of a stupid coloring. \end{center} \begin{center} Examples of clever colorings. The first coloring is missing a blue cell in the second row, and the second coloring has two yellow segments in the second column. \end{center} How many stupid colorings of the grid are there? Two colorings are considered different if there is some cell that is colored differently.
Before counting, we should understand the structure of a stupid coloring. First, both of the following cannot hold: There exists a path of yellow cells from column $1$ to column $m$. There exists a path of blue cells from row $1$ to row $n$. In fact, if two such paths existed, they must have a cell in common, and it would have to be blue and yellow at the same time. Without loss of generality, suppose statement 1 is false. Consider a yellow cell in the grid. All blue cells in its row must be to its left or right because they lie in one segment. So, each yellow cell either belongs to the connected component $A$ of yellow cells touching the first column or the component $B$ touching the last column. There cannot be a column with one cell in $A$ and another cell in $B$, otherwise the segment would connect the two components. And every column has at least one yellow cell, so there exists a number $c$ ($1\le c<m$) such that $A$ occupies the first $c$ columns and $B$ occupies the last $m-c$ columns. Let $[l_A, r_A]$ be the segment of yellow cells in column $c$ and $[l_B, r_B]$ be the segment of yellow cells in column $c+1$. Since the segments do not overlap, we either have $r_A<l_B$ or $r_B<l_A$. Without loss of generality, suppose $r_A<l_B$. The cells in $A$ create a monotonically increasing path from $(1,0)$ to $(r_A, c)$, then make a monotonically decreasing path from $(r_A, c-1)$ to $(n,0)$. A similar structure happens for $B$. The number of monotonic paths where we step right $a$ times and up $b$ times is counted by the binomial coefficient ${a+b\choose a}$. Now, if we fix $r_A$ and $l_B$, we can count the number of stupid colorings with the product of $4$ binomial coefficients. To make this fast enough, we can fix only $r_A$ and use a prefix sum to find the number of ways over all $l_B>r_A$. To generalize from the assumption that $r_A<l_B$, we can multiply the answer by $2$ since it's symmetric. To generalize from the assumption that statement $1$ is false, we can also count the number of ways if $n$ and $m$ are swapped. But we should be careful about double counting the case where both statements 1 and 2 are false. This can be handled without too much trouble by simply requiring $r_A+1<l_B$ for one of the two cases. Complexity is $O(\max(n, m)^2)$.
[ "combinatorics", "dp", "math" ]
3,100
#include <bits/stdc++.h> using namespace std; const int M = 998244353; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; if(n < m) swap(n, m); vector<vector<long long>> choose(n + m, vector<long long>(n)); for(int i = 0; i < n + m; i++) { for(int j = 0; j < n; j++) { if(j == 0) choose[i][j] = 1; else if(i == 0) choose[i][j] = 0; else choose[i][j] = (choose[i - 1][j] + choose[i - 1][j - 1]) % M; } } long long ans = 0; for(int r = 1; r < n; r++) { long long F = 0; for(int c = m - 1; c >= 1; c--) { F = (F + choose[n - r + m - c - 1][n - r] * choose[c + n - r - 1][n - r - 1]) % M; ans = (ans + choose[r + c - 1][r] * ((choose[m - c + r - 1][r - 1] * F) % M)) % M; } } swap(n, m); for(int r = 1; r < n; r++) { long long F = 0; for(int c = m - 1; c >= 1; c--) { ans = (ans + choose[r + c - 1][r] * ((choose[m - c + r - 1][r - 1] * F) % M)) % M; F = (F + choose[n - r + m - c - 1][n - r] * choose[c + n - r - 1][n - r - 1]) % M; } } ans = (2 * ans) % M; cout << ans << '\n'; }
1503
F
Balance the Cards
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules: - The empty sequence is balanced. - If $[a_1,\ldots,a_n]$ and $[b_1,\ldots, b_m]$ are balanced, then their concatenation $[a_1,\ldots,a_n,b_1,\ldots,b_m]$ is balanced. - If $x$ is a positive integer and $[a_1,\ldots,a_n]$ is balanced, then $[x,a_1,\ldots,a_n,-x]$ is balanced. The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, $[1, 2, -2, -1]$ and $[1, 3, -3, 2, -2, -1]$ are balanced, but $[1, 2, -1, -2]$ and $[-1, 1]$ are not balanced. There are $2n$ cards. Each card has a number on the front and a number on the back. Each integer $1,-1,2,-2,\ldots,n,-n$ appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card. You can reorder the cards however you like. You are \textbf{not} allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.
Suppose we have a deck of cards where the front and back are both balanced bracket sequences. Let's line the cards up horizontally and draw them as points. For each pair of matching brackets on the front and back, we will connect them with an edge. For matched brackets on the front, we add an edge as a semicircle lying above the points. And for matched brackets on the back, we add a similar edge below the points. Since every point is incident to exactly two edges, this graph decomposes into cycles. Since the edges are non-intersecting, each cycle is a Jordan curve in the plane. Imagine the curve as a track, and a monorail makes one full trip clockwise around the track. Each edge turns the monorail clockwise or counterclockwise by 180 degrees. Since the overall effect must turn the monorail a full 360 degrees clockwise, there are two more clockwise edges than counterclockwise edges in the cycle. If a cycle has $2m$ edges, then there are $m+1$ clockwise edges and $m-1$ counterclockwise edges. Now, in the actual problem we are given a shuffled deck of cards. If there exists a way to reorder them so that the front and back are both balanced, then we know the above property must hold. Even though the cards are shuffled, we still have enough information to construct the edges and distinguish two edges in the same cycle by orientation (clockwise and counterclockwise). If there are $m+1$ edges of one orientation, we should call them the clockwise edges. Otherwise if the number of edges of both orientations are invalid, we should report that no solution exists. Now that we have restricted ourselves to the case where this important condition holds, we should construct a solution. We can do this by solving for all the cycles independently and concatenating them together. Consider a cycle. Let's make a binary string describing the sequence of orientations, where $1$ denotes a clockwise turn and $0$ denotes a counterclockwise turn. Since there are $m+1$ clockwise turns, we can find two adjacent $1$'s in the string. For consistency, let's cyclically shift the string so that it begins and ends with $1$, and we can consider the curve to begin at the leftmost point. Let's see how we can build the curve recursively. First, there is the base case where the string is $11$. Clearly, we can build the curve with two points like this. Base Case: Now, suppose we have constructed a curve corresponding to $1s1$ for some string $s$. We will hide the turns of $s$ in the drawing, and just display it as a blue box. From this, we can build a curve corresponding to the string $10s11$ as shown on the right. This requires us to add two new points and reverse the order of the points in the blue box. Operation 1: Similarly, if we have constructed a curve for $1s1$, we can build the curve for $11s01$. Operation 2: Suppose we have constructed the curves $1s1$ and $1t1$ for two strings $s$ and $t$. The turns of $s$ are displayed as a blue box, and the turns of $t$ are displayed as a green box. Then we can build the curve $1st1$ as shown on the right. We take the last point in the blue box visited by the curve, and replace it with the points in the green box, in the same order. Operation 3: It turns out that the base case and these three operations are enough to build any curve satisfying the required condition. We can do it recursively as follows. If the string is $11$, return the base case. If the string is $10s11$ for some $s$, build the curve $1s1$ and apply operation 1. If the string is $11s01$ for some $s$, build the curve $1s1$ and apply operation 2. Otherwise, there exist non-empty strings $s$ and $t$ so that the string is $1st1$, and $s$ contains the same number of $0$'s and $1$'s (and thus so does $t$). Recursively build the curves $1s1$ and $1t1$, and apply operation 3. How can we apply these operations efficiently? When constructing a curve, we only care about the list of points (ignoring the leftmost one) as they appear from left to right, and which points are visited immediately before and after the leftmost point by the curve. If we store the list in the form of a doubly linked list, the operations of reversing and inserting in the middle can be done in constant time. To build it recursively, we also need an efficient way to find a splitting point in the case of $1st1$. If we just scan from one endpoint maintaining a prefix sum (number of $1$'s minus number of $0$'s), the algorithm will take $O(n^2)$ time overall. Instead, we should scan from both endpoints in parallel, and stop when one of them finds a splitting point. If it splits into lengths $k$ and $m-k$, then the time is given by the recurrence $T(m)=T(k)+T(m-k)+\min(k,m-k)=O(m\log m).$ Complexity is $O(n\log n)$. There is also an $O(n)$ solution. Scan the string $s$ (ignoring the first and last $1$) from left to right, maintaining a stack of linked lists. When the prefix sum (number of $1$'s minus number of $0$'s) increases in absolute value, we push the base case to the stack. When the prefix sum decreases in absolute value, we apply an operation $1$ or $2$ to the curve on the top of the stack, then merge the top two curves with operation $3$.
[ "constructive algorithms", "data structures", "divide and conquer", "geometry", "graphs", "implementation" ]
3,500
#include <bits/stdc++.h> using namespace std; struct curve { list<int> a, b; curve() {} curve(int x) { a.push_back(x); b.push_back(x); } curve& operator+=(curve &o) { a.splice(a.end(), o.a); o.b.splice(o.b.end(), b); b.swap(o.b); return *this; } curve& rev() { a.swap(b); return *this; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> openfront(n + 1), closefront(n + 1), openback(n + 1), closeback(n + 1), a(2 * n), b(2 * n); for(int i = 0; i < 2 * n; i++) { cin >> a[i] >> b[i]; if(a[i] > 0) openfront[a[i]] = i; else closefront[-a[i]] = i; if(b[i] > 0) openback[b[i]] = i; else closeback[-b[i]] = i; } vector<bool> vis(2 * n, false); vector<int> ans, ve; stack<int> st; stack<curve*> stnode; string s; for(int i = 0; i < 2 * n; i++) { if(!vis[i]) { ve.clear(); s.clear(); int x = i; int cnt = 0; do { ve.push_back(x); vis[x] = true; if(a[x] > 0) { cnt++; s.push_back('1'); x = closefront[a[x]]; }else { s.push_back('0'); x = openfront[-a[x]]; } ve.push_back(x); vis[x] = true; if(b[x] > 0) { s.push_back('0'); x = closeback[b[x]]; }else { cnt++; s.push_back('1'); x = openback[-b[x]]; } }while(x != i); if(cnt == (int) s.length() / 2 - 1) { cnt = s.length() - cnt; for(char &c : s) c = (c == '0' ? '1' : '0'); } if(cnt != (int) s.length() / 2 + 1) { cout << "NO\n"; return 0; } int idx = 0; while(s[idx] == '0' || s[idx + 1] == '0') idx++; rotate(s.begin(), s.begin() + idx, s.end()); rotate(ve.begin(), ve.begin() + idx, ve.end()); stnode.push(new curve(0)); for(int j = (int) s.length() - 1; j >= 2; j--) { if(st.empty() || s[st.top()] == s[j]) { st.push(j); stnode.push(new curve()); }else { curve *x = new curve(j), *y = new curve(st.top()), *z = stnode.top(); st.pop(); stnode.pop(); if(s[j] == '0') { *x += *y; *x += z->rev(); *x += *stnode.top(); stnode.pop(); stnode.push(x); }else { curve *w = stnode.top(); stnode.pop(); *w += z->rev(); *w += *y; *w += *x; stnode.push(w); } } } assert(st.empty()); assert((int) stnode.size() == 1); curve *y = stnode.top(); y->a.push_front(1); y->b.push_back(1); if(a[ve[1]] < 0) y->rev(); for(int idx : y->a) { ans.push_back(ve[idx]); } stnode.pop(); } } cout << "YES\n"; for(int i : ans) { cout << a[i] << ' ' << b[i] << '\n'; } }
1504
A
Déjà Vu
A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu. There is a string $s$. You \textbf{must} insert \textbf{exactly one} character 'a' somewhere in $s$. If it is possible to create a string that is \textbf{not} a palindrome, you should find one example. Otherwise, you should report that it is impossible. For example, suppose $s=$ "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.
If $s$ is the character 'a' repeated some number of times, there is no solution. Otherwise, I claim either 'a' + $s$ or $s$ + 'a' is a solution (or both). Let's prove it. Assume for contradiction that 'a' + $s$ and $s$ + 'a' are both palindromes. Then the first and last characters of $s$ are 'a'. Then the second and second to last characters of $s$ are 'a'. Repeating this, we see that all characters of $s$ are 'a', but we assumed we are not in this case. Therefore, the claim is true. The solution is simply to check if 'a' + $s$ and $s$ + 'a' are palindromes and output the correct one. Complexity is $O(n)$.
[ "constructive algorithms", "strings" ]
800
#include <bits/stdc++.h> using namespace std; bool palindrome(const string &s) { int n = s.length(); for(int i = 0; i < n; i++) { if(s[i] != s[n - i - 1]) return false; } return true; } int main() { ios::sync_with_stdio(false); cin.tie(0); int te; cin >> te; while(te--) { string s; cin >> s; if(!palindrome(s + 'a')) { cout << "YES\n" << s << 'a' << "\n"; }else if(!palindrome('a' + s)) { cout << "YES\n" << 'a' << s << '\n'; }else { cout << "NO\n"; } } }
1504
B
Flip the Bits
There is a binary string $a$ of length $n$. In one operation, you can select any prefix of $a$ with an \textbf{equal} number of $0$ and $1$ symbols. Then all symbols in the prefix are inverted: each $0$ becomes $1$ and each $1$ becomes $0$. For example, suppose $a=0111010000$. - In the first operation, we can select the prefix of length $8$ since it has four $0$'s and four $1$'s: $[01110100]00\to [10001011]00$. - In the second operation, we can select the prefix of length $2$ since it has one $0$ and one $1$: $[10]00101100\to [01]00101100$. - It is illegal to select the prefix of length $4$ for the third operation, because it has three $0$'s and one $1$. Can you transform the string $a$ into the string $b$ using some finite number of operations (possibly, none)?
Let's call a prefix legal if it contains an equal number of $0$ and $1$ symbols. The key observation is that applying operations never changes which prefixes are legal. In fact, suppose we apply an operation to a prefix of length $i$, and consider a prefix of length $j$. We want to show that if $j$ was legal before, it remains legal. And if it wasn't legal, it won't become legal. If $j<i$, then all bits in the length $j$ prefix are inverted. The numbers of $0$'s and $1$'s swap, so it cannot change whether they are equal, and hence it cannot change whether $j$ is legal. If $j\ge i$, then $i/2$ of the $0$ symbols become $1$ and $i/2$ of the $1$ symbols become $0$. So the numbers of both symbols do not change, so it cannot change whether $j$ is legal. Using prefix sums, we can determine for each prefix whether it is legal. Consider an index $i$. If $i=n$ and $a_n\ne b_n$, then we must flip the length $n$ prefix at some point. If $i<n$ and $a_i=b_i$, $a_{i+1}\ne b_{i+1}$, or $a_i\ne b_i$, $a_{i+1}=b_{i+1}$, then we must flip the length $i$ prefix at some point. If we flip precisely these prefixes in any order, it will transform $a$ into $b$. So we should simply check that every prefix that must be flipped is legal. Complexity is $O(n)$.
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; string a, b; cin >> n >> a >> b; a.push_back('0'); b.push_back('0'); int cnt = 0; for(int i = 0; i < n; i++) { cnt += (a[i] == '1') - (a[i] == '0'); if((a[i] == b[i]) != (a[i + 1] == b[i + 1]) && cnt != 0) { cout << "NO\n"; return; } } cout << "YES\n"; } int main() { ios::sync_with_stdio(false); cin.tie(0); int te; cin >> te; while(te--) { solve(); } }
1506
A
Strange Table
Polycarp found a rectangular table consisting of $n$ rows and $m$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm \textbf{"by columns"}: - cells are numbered starting from one; - cells are numbered from left to right by columns, and inside each column from top to bottom; - number of each cell is an integer one greater than in the previous cell. For example, if $n = 3$ and $m = 5$, the table will be numbered as follows: $$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} $$ However, Polycarp considers such numbering inconvenient. He likes the numbering \textbf{"by rows"}: - cells are numbered starting from one; - cells are numbered from top to bottom by rows, and inside each row from left to right; - number of each cell is an integer one greater than the number of the previous cell. For example, if $n = 3$ and $m = 5$, then Polycarp likes the following table numbering: $$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} $$ Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering \textbf{"by rows"}, if in the numbering \textbf{"by columns"} the cell has the number $x$?
To find the cell number in a different numbering, you can find $(r, c)$ coordinates of the cell with the number $x$ in the numbering "by columns": $r = ((x-1) \mod r) + 1$, where $a \mod b$ is the remainder of dividing the number $a$ by the number $b$; $c = \left\lceil \frac{x}{n} \right\rceil$, where $\left\lceil \frac{a}{b} \right\rceil$ is the division of the number $a$ to the number $b$ rounded up. Then, the cell number in numbering "by lines" will be equal to $(r-1)*m + c$.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { ll n, m, x; cin >> n >> m >> x; x--; ll col = x / n; ll row = x % n; cout << row * m + col + 1 << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; while (n--) { solve(); } }
1506
B
Partial Replacement
You are given a number $k$ and a string $s$ of length $n$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: - The first character '*' in the original string should be replaced with 'x'; - The last character '*' in the original string should be replaced with 'x'; - The distance between two neighboring replaced characters 'x' must not exceed $k$ (more formally, if you replaced characters at positions $i$ and $j$ ($i < j$) and at positions $[i+1, j-1]$ there is no "x" symbol, then $j-i$ must be no more than $k$). For example, if $n=7$, $s=$.**.*** and $k=3$, then the following strings will satisfy the conditions above: - .xx.*xx; - .x*.x*x; - .xx.xxx. But, for example, the following strings will not meet the conditions: - .**.*xx (the first character '*' should be replaced with 'x'); - .x*.xx* (the last character '*' should be replaced with 'x'); - .x*.*xx (the distance between characters at positions $2$ and $6$ is greater than $k=3$). Given $n$, $k$, and $s$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.
To solve this problem, you can use the dynamic programming method or the greedy algorithm. Let's describe the greedy solution. Until we get to the last character '*' we will do the following: being in position $i$, find the maximum $j$, such that $s_j=$'*' and $j-i \le k$, and move to position $j$. Since we make the longest move on each turn, we will make the minimum number of substitutions.
[ "greedy", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; string s; cin >> s; int res = 1; int i = s.find_first_of('*'); while (true) { int j = min(n - 1, i + k); for (; i < j && s[j] == '.'; j--) {} if (i == j) { break; } res++; i = j; } cout << res << "\n"; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1506
C
Double-ended Strings
You are given the strings $a$ and $b$, consisting of lowercase Latin letters. You can do any number of the following operations in any order: - if $|a| > 0$ (the length of the string $a$ is greater than zero), delete the first character of the string $a$, that is, replace $a$ with $a_2 a_3 \ldots a_n$; - if $|a| > 0$, delete the last character of the string $a$, that is, replace $a$ with $a_1 a_2 \ldots a_{n-1}$; - if $|b| > 0$ (the length of the string $b$ is greater than zero), delete the first character of the string $b$, that is, replace $b$ with $b_2 b_3 \ldots b_n$; - if $|b| > 0$, delete the last character of the string $b$, that is, replace $b$ with $b_1 b_2 \ldots b_{n-1}$. Note that after each of the operations, the string $a$ or $b$ may become empty. For example, if $a=$"hello" and $b=$"icpc", then you can apply the following sequence of operations: - delete the first character of the string $a$ $\Rightarrow$ $a=$"ello" and $b=$"icpc"; - delete the first character of the string $b$ $\Rightarrow$ $a=$"ello" and $b=$"cpc"; - delete the first character of the string $b$ $\Rightarrow$ $a=$"ello" and $b=$"pc"; - delete the last character of the string $a$ $\Rightarrow$ $a=$"ell" and $b=$"pc"; - delete the last character of the string $b$ $\Rightarrow$ $a=$"ell" and $b=$"p". For the given strings $a$ and $b$, find the minimum number of operations for which you can make the strings $a$ and $b$ equal. Note that empty strings are also equal.
Regarding to the small constraints, in this problem you could iterate over how many characters were removed by each type of operation. If $l$ characters at the beginning and $x$ characters at the end are removed from the string $s$, then the substring $s[l+1, n-x]$ remains, where $n$ - is the length of the string $s$. There is also a fast solution to this problem using dynamic programming.
[ "brute force", "implementation", "strings" ]
1,000
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { string a, b; cin >> a >> b; int n = a.size(), m = b.size(); int ans = 0; for (int len = 1; len <= min(n, m); len++) { for (int i = 0; i + len <= n; i++) { for (int j = 0; j + len <= m; j++) { if (a.substr(i, len) == b.substr(j, len)) { ans = max(ans, len); } } } } cout << a.size() + b.size() - 2 * ans << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; while (n--) { solve(); } }
1506
D
Epic Transformation
You are given an array $a$ of length $n$ consisting of integers. You can apply the following operation, consisting of several steps, on the array $a$ \textbf{zero} or more times: - you select two \textbf{different} numbers in the array $a_i$ and $a_j$; - you remove $i$-th and $j$-th elements from the array. For example, if $n=6$ and $a=[1, 6, 1, 1, 4, 4]$, then you can perform the following sequence of operations: - select $i=1, j=5$. The array $a$ becomes equal to $[6, 1, 1, 4]$; - select $i=1, j=2$. The array $a$ becomes equal to $[1, 4]$. What can be the minimum size of the array after applying some sequence of operations to it?
Let's replace each character with the number of its occurrences in the string. Then each operation - take two non-zero numbers and subtract one from them. In the end, we will have only one non-zero number left, and we want to minimize it. We can say that we want to minimize the maximum number after applying all the operations, which means we want to minimize the maximum number at each step. We get the following greedy solution - each time we take two characters with maximal occurrences number and delete them.
[ "constructive algorithms", "data structures", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { priority_queue<pair<int, int>> q; int n; cin >> n; map<int, int> v; for (int i = 0; i < n; i++) { int x; cin >> x; v[x]++; } for (auto [x, y] : v) { q.push({y, x}); } int sz = n; while (q.size() >= 2) { auto [cnt1, x1] = q.top(); q.pop(); auto [cnt2, x2] = q.top(); q.pop(); cnt1--; cnt2--; sz -= 2; if (cnt1) { q.push({cnt1, x1}); } if (cnt2) { q.push({cnt2, x2}); } } cout << sz << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; while (n--) { solve(); } }
1506
E
Restoring the Permutation
A permutation is a sequence of $n$ integers from $1$ to $n$, in which all numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ are permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ are not. Polycarp was presented with a permutation $p$ of numbers from $1$ to $n$. However, when Polycarp came home, he noticed that in his pocket, the permutation $p$ had turned into an array $q$ according to the following rule: - $q_i = \max(p_1, p_2, \ldots, p_i)$. Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him. An array $a$ of length $n$ is lexicographically smaller than an array $b$ of length $n$ if there is an index $i$ ($1 \le i \le n$) such that the first $i-1$ elements of arrays $a$ and $b$ are the same, and the $i$-th element of the array $a$ is less than the $i$-th element of the array $b$. For example, the array $a=[1, 3, 2, 3]$ is lexicographically smaller than the array $b=[1, 3, 4, 2]$. For example, if $n=7$ and $p=[3, 2, 4, 1, 7, 5, 6]$, then $q=[3, 3, 4, 4, 7, 7, 7]$ and the following permutations could have been as $p$ initially: - $[3, 1, 4, 2, 7, 5, 6]$ (lexicographically minimal permutation); - $[3, 1, 4, 2, 7, 6, 5]$; - $[3, 2, 4, 1, 7, 5, 6]$; - $[3, 2, 4, 1, 7, 6, 5]$ (lexicographically maximum permutation). For a given array $q$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.
If we want to build a minimal lexicographic permutation, we need to build it from left to right by adding the smallest possible element. If $q[i] = q[i-1]$, so the new number must not be greater than all the previous ones, and if $q[i] > q[i-1]$, then necessarily $a[i] = q[i]$. $q[i] < q[i-1]$ does not happen, since $q[i]$ - is the maximum element among the first $i$ elements. We get a greedy solution if $q[i] > q[i-1]$, then $a[i] = q[i]$, otherwise we put the minimum character that has not yet occurred in the permutation.
[ "constructive algorithms", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; void placeLeft(vector<int> &q, bool minimize) { set<int> left; for (int i = 1; i <= (int) q.size(); i++) { left.insert(i); } for (int i : q) { if (i != -1) { left.erase(i); } } int lastPlaced = -1; for (int &i : q) { if (i == -1) { set<int>::const_iterator it; if (minimize) { it = left.begin(); } else { it = --left.lower_bound(lastPlaced); } i = *it; left.erase(it); } else { lastPlaced = i; } } } void solve() { int n; cin >> n; vector<int> q(n); for (int i = 0; i < n; i++) { cin >> q[i]; } vector<int> res1(n, -1), res2(n, -1); for (int i = 0, lastPlaced = -1; i < n; lastPlaced = q[i], i++) { if (lastPlaced != q[i]) { res1[i] = q[i]; res2[i] = q[i]; } } placeLeft(res1, true); placeLeft(res2, false); for (int x : res1) { cout << x << " "; } cout << "\n"; for (int x : res2) { cout << x << " "; } cout << "\n"; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1506
F
Triangular Paths
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $(r, c)$ ($1 \le c \le r$), where $r$ is the number of the layer, and $c$ is the number of the point in the layer. From each point $(r, c)$ there are two \textbf{directed} edges to the points $(r+1, c)$ and $(r+1, c+1)$, but only one of the edges is activated. If $r + c$ is even, then the edge to the point $(r+1, c)$ is activated, otherwise the edge to the point $(r+1, c+1)$ is activated. Look at the picture for a better understanding. \begin{center} {\small Activated edges are colored in black. Non-activated edges are colored in gray.} \end{center} From the point $(r_1, c_1)$ it is possible to reach the point $(r_2, c_2)$, if there is a path between them only from \textbf{activated} edges. For example, in the picture above, there is a path from $(1, 1)$ to $(3, 2)$, but there is no path from $(2, 1)$ to $(1, 1)$. Initially, you are at the point $(1, 1)$. For each turn, you can: - Replace activated edge for point $(r, c)$. That is if the edge to the point $(r+1, c)$ is activated, then \textbf{instead of it}, the edge to the point $(r+1, c+1)$ becomes activated, otherwise if the edge to the point $(r+1, c+1)$, then \textbf{instead if it}, the edge to the point $(r+1, c)$ becomes activated. This action increases the cost of the path by $1$; - Move from the current point to another by following the activated edge. This action \textbf{does not increase} the cost of the path. You are given a sequence of $n$ points of an infinite triangle $(r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n)$. Find the minimum cost path from $(1, 1)$, passing through all $n$ points in \textbf{arbitrary} order.
Since all edges are directed downward, there is only one way to visit all $n$ points is to visit the points in ascending order of the layer number. Let's sort the points in order of increasing layer. It is easy to see that the cost of the entire path is equal to the sum of the cost of paths between adjacent points. Let's learn how to calculate the cost of a path between two points $(r_1, c_1)$ and $(r_2, c_2)$: If $r_1 - c_1 = r_2 - c_2$, then if $(r_1 + c_1)$ is even, then the cost is $r_2-r_1$, otherwise the cost is $0$; Otherwise, move the point $(r_2, c_2)$ to $(r_3, c_3) = (r_2-r_1+1, c_2-c_1+1)$ and find the cost of the path $(1, 1) \rightarrow (r_3, c_3)$ with different criteria for the activation of the edges; If $(r_1 + c_1)$ is even then the cost is $\lfloor \frac{r_3-c_3}{2} \rfloor$; Otherwise, the cost is $\lceil \frac{r_3-c_3}{2} \rceil$;
[ "constructive algorithms", "graphs", "math", "shortest paths", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; bool isLeftArrow(int r, int c) { return (r + c) % 2 == 0; } bool isRightArrow(int r, int c) { return (r + c) % 2 == 1; } int calcDist(int r1, int c1, int r2, int c2) { if (r1 - c1 == r2 - c2) { return isRightArrow(r1, c1) ? 0 : r2 - r1; } r2 -= r1 - 1; c2 -= c1 - 1; if (isLeftArrow(r1, c1)) { return (r2 - c2) / 2; } else { return (r2 - c2 + 1) / 2; } } void solve() { int n; cin >> n; vector<int> r(n); vector<int> c(n); for (int i = 0; i < n; i++) { cin >> r[i]; } for (int i = 0; i < n; i++) { cin >> c[i]; } vector<pair<int, int>> pts; for (int i = 0; i < n; i++) { pts.emplace_back(r[i], c[i]); } sort(pts.begin(), pts.end()); int curR = 1, curC = 1; int res = 0; for (auto[nextR, nextC] : pts) { res += calcDist(curR, curC, nextR, nextC); curR = nextR; curC = nextC; } cout << res << "\n"; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1506
G
Maximize the Remaining String
You are given a string $s$, consisting of lowercase Latin letters. While there is at least one character in the string $s$ that is \textbf{repeated at least twice}, you perform the following operation: - you choose the index $i$ ($1 \le i \le |s|$) such that the character at position $i$ occurs \textbf{at least two} times in the string $s$, and delete the character at position $i$, that is, replace $s$ with $s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n$. For example, if $s=$"codeforces", then you can apply the following sequence of operations: - $i=6 \Rightarrow s=$"codefrces"; - $i=1 \Rightarrow s=$"odefrces"; - $i=7 \Rightarrow s=$"odefrcs"; Given a given string $s$, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string \textbf{become unique}. A string $a$ of length $n$ is lexicographically less than a string $b$ of length $m$, if: - there is an index $i$ ($1 \le i \le \min(n, m)$) such that the first $i-1$ characters of the strings $a$ and $b$ are the same, and the $i$-th character of the string $a$ is less than $i$-th character of string $b$; - \textbf{or} the first $\min(n, m)$ characters in the strings $a$ and $b$ are the same and $n < m$. For example, the string $a=$"aezakmi" is lexicographically less than the string $b=$"aezus".
How can you check if you can perform such a sequence of operations on the string $s$ to get the string $t$? Note that each time we delete an arbitrary character that is repeated at least two times, so $t$ must be a subsequence of the string $s$ and have the same character set as the string $s$. We will consequently build the resulting string $t$, adding characters to the end. To check if there is such a sequence of operations that turns the string $s$ into the string $tc?$ (a string that first contains the characters of the string $t$, then the character $c$, and then some unknown characters), it is enough to do the following: Find the minimum index $i$ such that $t$ is included in $s[1..i]$ as a subsequence; Find the minimum index $j$ ($i<j$) such that $s_j = c$; Then the substring $s[j+1..n]$ must contain all characters that are in the string $s$, but which are not in the string $tc$. Let's denote a function that checks the criterion above as $can(t)$. Having received the verification criterion, the following algorithm can be made: Initially $t$ is an empty string; While there is a character in the string $s$ that is not in the string $t$, we will find the maximum character $c$ not contained in $t$, but contained in $s$, for which $can(tc) = true$ and add it to the end of the string $t$. Since at each step we take the maximum symbol for which the criterion is met, the resulting string $t$ will be the lexicographically maximum.
[ "brute force", "data structures", "dp", "greedy", "strings" ]
2,000
#include <bits/stdc++.h> using namespace std; int distinct(string s) { sort(s.begin(), s.end()); return unique(s.begin(), s.end()) - s.begin(); } string filter(const string &s, char c) { string t; bool foundFirst = false; for (char a : s) { if (a != c && foundFirst) { t += a; } else if (a == c) { foundFirst = true; } } return t; } void solve() { string s; cin >> s; int m = distinct(s); unordered_set<char> used(s.begin(), s.end()); string t; while (m > 0) { char maxC = -1; for (char c : used) { if (distinct(filter(s, c)) == m - 1) { maxC = max(maxC, c); } } t += maxC; s = filter(s, maxC); used.erase(maxC); m--; } cout << t << "\n"; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1508
A
Binary Literature
A bitstring is a string that contains only the characters 0 and 1. Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length $2n$. A valid novel for the contest is a bitstring of length at most $3n$ that contains \textbf{at least two} of the three given strings as subsequences. Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest. A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) characters.
First solution Let's focus on two bitstrings $s$ and $t$. How can we get a short string that has them both as subsequences? Well, suppose both strings have a common subsequence of length $L$. Then we can include this subsequence as part of our string. Then we just place the remaining characters of both sequences in the correct positions between the characters of this common sequence, to make both strings a subsequence of the result. This saves us $L$ characters compared to just concatenating $s$ and $t$ since the characters of the common subsequence only have to included once, i.e. this uses $|s| + |t| - L$ characters. Now, in our problem, all strings have a length of $2n$, so this algorithm will use a total of $4n - L$ characters. This means if we can find two strings that have a common subsequence of length $n$, we can finish the problem. However, the usual algorithm for computing the longest common subsequence works in $\mathcal{O}(n^2)$, which is unlikely to pass the time limit, so we have to construct this common subsequence more concretely. The observation is that because each character is either $0$ or $1$, one of these characters must appear at least $n$ times. Call such a character frequent. Now since each string has at least one frequent character, two of these frequent characters are equal. Considering these two strings and their frequent character we find a common subsequence of length $n$, equal to either $000\dots 0$ or $111\dots 1$. Second solution This solution uses a similar idea, in a way that is a bit easier to implement. Consider three pointers $p_1, p_2, p_3$, pointing to a character in each string, and a string $t$ representing our answer. These pointers will represent the prefixes of each string that we have represented in our answer. Initially, $t$ is empty and $p_1 = p_2 = p_3 = 1$ (here our strings are $1$-indexed). Now we will add characters to $t$ one by one. At each step, consider the three characters pointed at by our three pointers. Since they are either $0$ or $1$, two of them are equal. Add this equal character to $t$, and advance the pointers that match this character by $1$. Continue this algorithm until one of the strings is completely contained in $t$, let's say $s_1$. At this point, suppose $t$ has $k$ characters, and thus the pointers have advanced by at least $2k$, since at least two of them advance on each step. We have exhausted the characters of $s_1$, so we have advanced $p_1$ by $2n$, and the other two pointers have advanced $2k - 2n$, and thus one of them has advanced by at least $k - n$. Now just add the remaining characters of this string to $t$. There are at most $2n - (k - n) = 3n - k$ of them, so in the end $t$ has at most $3n$ characters. This problem was originally suggested as a 2B. It turned out to be too hard and was switched to 2C, before being further switched to 1A because it was still too hard. Some testers still believed this problem to be even harder, but we ended up deciding to have it as 1A with a larger score than usual. Apologies to the testers who had to solve this as if it was the second easiest problem in the contest :^)
[ "constructive algorithms", "greedy", "implementation", "strings", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; string mix(string s, string t, char c) { int n = s.size()/2; vector<int> v1 = {-1}, v2 = {-1}; for(int i = 0; i < 2 * n; i++) { if(s[i] == c) v1.push_back(i); if(t[i] == c) v2.push_back(i); } string ans; for(int i = 0; i < n; i++) { for(int j = v1[i] + 1; j < v1[i + 1]; j++) ans += s[j]; for(int j = v2[i] + 1; j < v2[i + 1]; j++) ans += t[j]; ans += c; } for(int j = v1[n] + 1; j < 2 * n; j++) ans += s[j]; for(int j = v2[n] + 1; j < 2 * n; j++) ans += t[j]; return ans; } void solve() { vector<string> s0, s1; int n; cin >> n; for(int i = 0; i < 3; i++) { string s; cin >> s; int cnt_0 = 0; for(auto &c : s) { if(c == '0') cnt_0++; } if(cnt_0 >= n) s0.push_back(s); else s1.push_back(s); } if(s0.size() >= 2) cout << mix(s0[0], s0[1], '0') << '\n'; else cout << mix(s1[0], s1[1], '1') << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) solve(); }
1508
B
Almost Sorted
Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation $a_1, a_2, \dots, a_n$ of $1, 2, \dots, n$ is said to be almost sorted if the condition $a_{i + 1} \ge a_i - 1$ holds for all $i$ between $1$ and $n - 1$ inclusive. Maki is considering the list of all almost sorted permutations of $1, 2, \dots, n$, given in lexicographical order, and he wants to find the $k$-th permutation in this list. Can you help him to find such permutation? Permutation $p$ is lexicographically smaller than a permutation $q$ if and only if the following holds: - in the first position where $p$ and $q$ differ, the permutation $p$ has a smaller element than the corresponding element in $q$.
First solution. Let's first analyze the general structure of an almost sorted permutation. We know that when the sequence decreases, it must decrease by exactly $1$. Thus, every decreasing subarray covers some consecutive range of values. Let's split the permutation into decreasing subarrays, each of them as large as possible. For example, we can split the almost sorted permutation $[3, 2, 1, 4, 6, 5, 7]$ as $[3, 2, 1], [4], [6, 5], [7]$. The main claim goes as follows. Claim. Each almost sorted permutation is determined uniquely by the sequence of sizes of its maximal decreasing subarrays. So for instance, in the previous example, the sequence of sizes $3, 1, 2, 1$ uniquely determines the permutation as $[3, 2, 1, 4, 6, 5, 7]$. This is because the last element $a_i$ of a decreasing block must be smaller than the first element $a_{i + 1}$ in the next block. Otherwise we either have $a_{i + 1} = a_i - 1$, in which case we should expand the previous block, or $a_{i + 1} < a_i - 1$, which is contradictory. Now, this is basically enough to get a complete solution. Through some careful counting (which we will go into detail about later) we can show that there are $2^{n - 1}$ almost sorted permutations of size $n$. Now notice that smaller sizes for the first block produce lexicographically smaller permutations (since a permutation whose first block has size $m$ starts with $m$). Moreover, the remaining sequence after deleting the first block is almost sorted. This enables to do a recursive argument to find the permutation, by first choosing the correct size for the first block and then solving recursively for the remaining sequence. This works in $\mathcal{O}(n \log k)$. Second solution. But we can do better. Let's mark the positions in the array where a decreasing block ends with $0$, and the other positions as $1$. Notice that the last character is always $0$, so we will ignore it and assign only the other $n - 1$ characters. Thus our example permutation $[3, 2, 1, 4, 6, 5, 7]$ becomes $110010$ since the first, second, and third blocks end at positions $3$, $4$, and $6$. By the first claim, we can recover the permutation from this sequence (which is also the proof of there being $2^{n - 1}$ permutations of size $n$ that we promised earlier!). Now, we can read the assigned sequence as a binary number, for instance, the corresponding number is $110010_2 = 2^5 + 2^4 + 2^1 = 50$ for our trusty example. The point of doing this is the following: Claim 2. The $k$-th almost sorted permutation in lexicographical order is assigned the number $k - 1$. To prove this it's actually enough to check that the number $m + 1$ is assigned to a greater permutation than the number $m$. This can be done by looking at how the permutation changes when we add $1$ to $m$, looking at the binary representation of $m$ from right to left. We leave it to the reader to fill in the details of the proof, but here's a diagram showing the situation graphically (with height representing the values of the permutation). Anyways, once we have proven this claim, we get a simple $\mathcal{O}(n + \log k)$ solution by finding the binary representation of $k$ and using it to reconstruct the blocks in $\mathcal{O}(n)$. This problem's creation has a funny story. Back when we were coming up with problems for Round 668, I (Ari) came up the following relatively simple and standard problem and shared it. The next day, Kuroni saw the problem, but misread it and ended up solving the version that made it into this contest, which we think is a lot cooler! One more fun fact for your consideration: This problem's name in Polygon is "sorrow".
[ "binary search", "combinatorics", "constructive algorithms", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; ll k; cin >> n >> k; if(n < 62 && k > 1LL << (n - 1)) { cout << "-1\n"; return; } string s; for(int i = 0; i < n; i++) s += '0'; k--; for(ll b = 0; b < min(60LL, (ll)(n - 1)); b++) { if((k >> b) & 1) s[n - 2 - b] = '1'; } int cur = 1, sz = 1; vector<int> ans; for(int i = 0; i < n; i++) { if(s[i] == '0') { for(int j = cur + sz - 1; j >= cur; j--) ans.push_back(j); cur += sz; sz = 1; } else sz++; } for(auto &x : ans) cout << x << " "; cout << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) solve(); }
1508
C
Complete the MST
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with $n$ nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with \textbf{non-negative weights} so that in the resulting fully-assigned complete graph the XOR sum of all weights would be equal to $0$. Define the ugliness of a fully-assigned complete graph the weight of its minimum spanning tree, where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with $n$ nodes contains all edges $(u, v)$ with $1 \le u < v \le n$; such a graph has $\frac{n(n-1)}{2}$ edges. She is not sure how to solve this problem, so she asks you to solve it for her.
Call $x$ the XOR sum of the weights of all pre-assigned edges. Lemma. All but one unassigned edges are assigned with $0$, while the remaining unassigned edge is assigned with $x$. Proof. Consider any assignment of unassigned edges. There are two cases on the minimum spanning tree: The MST does not use all unassigned edges: We can assign one unused unassigned edge with $x$, while all other unassigned edges (including all used in the MST) are assigned with $0$. This reduces the weight of the MST. The MST uses all unassigned edges: We can prove that the sum of weights of unassigned edges is at least $x$, and the equality can be achieved with the construction from the lemma. Intuitively, the XOR sum is an "uncarried" summation, and the construction from the lemma removes any digit carry. Let's DFS on the unassigned edges. It can happen that the unassigned edges may separate the graph into multiple components, and we might need to use some pre-assigned edges in our MST. I will divide the collection of pre-assigned edges into 3 types: Edges that must be included in the MST: these are edges with smallest weights that connect the components after traversing through unassigned edges. Edges that cannot be included in the MST: these are edges that form cycles with smaller-weighted pre-assigned edges. In other words, these are edges that do not exist in the minimum spanning forest of the pre-assigned edges. Edges that are in neither of the previous types. For the unassigned edges, there are two cases: The unassigned edges form at least a cycle: We can assign any edge on this cycle as $x$, the rest as $0$, then build an MST using the $0$-weighted edges with pre-assigned edges of type 1. The unassigned edges does not form a cycle. Suppose we build the tree using only unassigned edges and edges of type 1. Then any edge of type 3 can replace an unassigned edge in the tree. That is because the edges of type 3 must form a cycle with edges of type 1 and unassigned edges (else it would either be in type 1 or type 2). We can simply replace an unassigned edge in that cycle with this type 3 edge. Therefore, for this case, our solution is to first form the tree with all edges of type 1 and unassigned edge. Then, if the smallest weighted type 3 edge has weight $< x$, we can replace an unassigned edge with this edge; else, we keep the tree. Therefore, for this case, our solution is to first form the tree with all edges of type 1 and unassigned edge. Then, if the smallest weighted type 3 edge has weight $< x$, we can replace an unassigned edge with this edge; else, we keep the tree. If the unassigned edges in the graph don't form a forest, then the answer is simply the weight of the MST where all the unassigned edges have weight $0$. Thus the interesting tests in this problem require these edges to form a forest, which means $m \ge \frac{n(n - 1)}{2} - (n - 1)$. This automatically limits the maximum value of $n$ to approximately $2\sqrt{m}$. Concretely, $n \le 633$ for all interesting tests in this problem. You can also use this to obtain a solution that runs in $O(m \sqrt{m})$, which a tester found, and which passes if implemented reasonably.
[ "bitmasks", "brute force", "data structures", "dfs and similar", "dsu", "graphs", "greedy", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 200005; int n, m, u, v, w, lef; long long rem, ans = 0; set<int> ava; vector<int> adj[N]; vector<array<int, 3>> ed; struct dsu { int par[N]; void init() { fill(par + 1, par + n + 1, -1); } int trace(int u) { return par[u] < 0 ? u : par[u] = trace(par[u]); } bool connect(int u, int v) { if ((u = trace(u)) == (v = trace(v))) { return false; } if (par[u] > par[v]) { swap(u, v); } par[u] += par[v]; par[v] = u; return true; } } all, ori; void DFS(int u) { ava.erase(u); sort(adj[u].begin(), adj[u].end()); for (int v = 0;;) { auto it = ava.lower_bound(v); if (it == ava.end()) { return; } v = *it; if (!binary_search(adj[u].begin(), adj[u].end(), v)) { all.connect(u, v); DFS(v); rem--; } v++; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; rem = 1LL * n * (n - 1) / 2 - m; for (int i = 1; i <= n; i++) { ava.insert(i); } all.init(); ori.init(); for (int i = 1; i <= m; i++) { cin >> u >> v >> w; adj[u].push_back(v); adj[v].push_back(u); lef ^= w; ed.push_back({w, u, v}); } for (int i = 1; i <= n; i++) { if (ava.count(i)) { DFS(i); } } if (rem > 0) { lef = 0; } sort(ed.begin(), ed.end()); for (auto [w, u, v] : ed) { if (all.connect(u, v)) { ans += w; ori.connect(u, v); } else if (ori.connect(u, v)) { lef = min(lef, w); } } cout << ans + lef << '\n'; }
1508
D
Swap Pass
Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem! You are given $n$ points on the plane, no three of which are collinear. The $i$-th point initially has a label $a_i$, in such a way that the labels $a_1, a_2, \dots, a_n$ form a permutation of $1, 2, \dots, n$. You are allowed to modify the labels through the following operation: - Choose two distinct integers $i$ and $j$ between $1$ and $n$. - Swap the labels of points $i$ and $j$, and finally - Draw the segment between points $i$ and $j$. A sequence of operations is valid if after applying all of the operations in the sequence in order, the $k$-th point ends up having the label $k$ for all $k$ between $1$ and $n$ inclusive, and the drawn segments don't intersect each other internally. Formally, if two of the segments intersect, then they must do so at a common endpoint of both segments. In particular, all drawn segments must be distinct. Find any valid sequence of operations, or say that none exist.
As it turns out, it is always possible to find the required sequence, no matter the position of the points in the plane and the initial permutation. It turns out that it's pretty hard to analyze even particular positions of the points, and it will be more convenient to start by analyzing particular permutations instead. To this effect, we will begin by doing two things: Ignore every $i$ such that initially $a_i = i$. Since we'll prove that the sequence exists for any configuration anyway, they can't ever matter. Draw an arrow from point $i$ to point $a_i$ for each $i$. This divides the points into a bunch of cycles. Now we can make the following observation: Observation 1. If we have any cycle, we can get all the balls in that cycle to their correct position by choosing any member $i$ in the cycle, and repeatedly swap passing between $i$ and $a_i$, without generating any intersections. This allows us to solve the problem for any position of the points as long as the permutation has a single cycle. However, this will generally not be the case. We can hope to deal with this by making a second observation. Observation 2. If we have any two distinct cycles and any two members $u$ and $v$ in those two cycles, then swap passing between $u$ and $v$ will merge both cycles. By combining both observations we can come up with the following general idea to solve any case: First, perform swaps between distinct cycles until all of the cycles merge into a single one. Then, move all the balls to their correct positions as described in the first observation. Now we just have to figure out how to perform these moves without having intersections between segments. It might be helpful to think about the case when the points are vertices of a convex polygon first since it simplifies the model without sacrificing too much of the geometry. Either way, we will describe only the general case. Consider any point, which we will use as a "pivot" for the operations at the end. Now, sort all of the other points by the angle of the segment between them and the pivot point. Call the segments that join two consecutive points in the ordering border segments, and the segments between the pivot and the other points central segments. Now we will just merge all the cycles by using border segments and then move all the balls to their intended position by using central segments, this solves the problem. However, there's one small special case that we might have to deal with depending on how we're thinking about the problem: If the pivot point we chose is on the convex hull of the set of points, then one of the border segments may actually intersect some other segments! Luckily, we can easily prove that this can't happen for more than one of the segments, so our plan still works. There are many different ways to deal with this case. From simplest to most complicated: Always choose the bottom-most and left-most point as a pivot. This makes this potentially troublesome segment predictable, and also allows us to slightly simplify the angular sorting code. Discard the problematic segment by looking at which pair of consecutive points makes a clockwise turn instead of a counter-clockwise turn. Discard the problematic segment by brute-force intersecting each border segment with each central segment. This increases our complexity to $\mathcal{O}(n^2)$, but this is still fine. Intentionally choose a pivot that is not on the convex hull and do something slightly different if the points are the vertices of a convex polygon. Regardless of how we choose to deal with it, we can now solve the problem with approximately $\frac{3}{2}n$ operations in the worst case, and a time complexity of either $\mathcal{O}(n \log n)$ or $\mathcal{O}(n^2)$ depending on how we implement the solution. This problem was originally proposed with the points always being the vertices of a convex polygon. This allows us to do a slightly different solution where we first merge the cycles and choose the pivot afterwards by choosing a point unaffected by the previous swaps. The reason for having $n = 2000$ in this problem rather than a larger $n$ like $10^5$ is because of the validator: it is essential to not have three collinear points in this problem, and I don't know how to check this for large $n$. The small $n$ also makes the checker much easier to write, though it's possible (albeit tricky) to write a checker that works in $O(n \log n)$. Regarding the number of operations used: The solution described in the editorial uses approximately $\frac{3}{2}n$ operations in the worst case when the permutation consists of cycles of size $2$. The minimum number of operations is lower bounded by $n - 1$ by combinatorics reasons when the permutation is a single cycle. Moreover, by Euler's formula, we have an upper bound of $3n - 6$ operations for any valid sequence, which goes down to $2n - 3$ when the points are the vertices of a convex polygon. I don't know of a solution that uses $cn$ operations for some $c < 3/2$, nor do I know of a general test case where it can be proven that at least $cn$ operations are needed for some $c > 1$, so I'd be really interested in seeing either.
[ "constructive algorithms", "geometry", "sortings" ]
3,000
#include <bits/stdc++.h> using namespace std; using ll = long long; struct point { ll x, y; point(ll _x = 0, ll _y = 0) : x(_x), y(_y) {} point operator- (const point &o) const { return point(x - o.x, y - o.y); } int half() { return y < 0 || (y == 0 && x < 0); } }; ll cross(point p, point q) { return p.x * q.y - p.y * q.x; } bool cmp(point p, point q) { if(p.half() != q.half()) { return p.half() < q.half(); } return cross(p, q) > 0; } const int MAXN = 2005; point ps[MAXN]; int n, a[MAXN], cyc[MAXN]; vector<int> in_cyc[MAXN]; vector<array<int, 2>> ops; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1; i <= n; i++) { cin >> ps[i].x >> ps[i].y >> a[i]; } int cur_cyc = 0, piv = 0; for(int i = 1; i <= n; i++) { if(a[i] == i || cyc[i]) continue; cur_cyc++; int u = i; do { cyc[u] = cur_cyc; in_cyc[cur_cyc].push_back(u); u = a[u]; } while(!cyc[u]); piv = i; } vector<int> to_sort; for(int i = 1; i <= n; i++) { if(a[i] == i || i == piv) continue; to_sort.push_back(i); } if(to_sort.empty()) { cout << "0\n"; return 0; } sort(to_sort.begin(), to_sort.end(), [&](int i, int j){ return cmp(ps[i] - ps[piv], ps[j] - ps[piv]); } ); vector<array<int, 2>> pairs; to_sort.push_back(to_sort[0]); for(int i = 0; i + 1 < to_sort.size(); i++) { if(cross(ps[to_sort[i]] - ps[piv], ps[to_sort[i + 1]] - ps[piv]) > 0) pairs.push_back({to_sort[i], to_sort[i + 1]}); } for(auto &[i, j] : pairs) { int c1 = cyc[i], c2 = cyc[j]; if(c1 != c2) { for(auto &x : in_cyc[c2]) { cyc[x] = c1; in_cyc[c1].push_back(x); } in_cyc[c2].clear(); ops.push_back({i, j}); swap(a[i], a[j]); } } while(a[piv] != piv) { int u = a[piv]; ops.push_back({piv, u}); swap(a[piv], a[u]); } cout << ops.size() << '\n'; for(auto &[i, j] : ops) cout << i << " " << j << '\n'; }
1508
E
Tree Calendar
Yuu Koito and Touko Nanami are newlyweds! On the wedding day, Yuu gifted Touko a directed tree with $n$ nodes and rooted at $1$, and a labeling $a$ which is some DFS order of the tree. Every edge in this tree is directed away from the root. After calling dfs(1) the following algorithm returns $a$ as a DFS order of a tree rooted at $1$ : \begin{verbatim} order := 0 a := array of length n function dfs(u): order := order + 1 a[u] := order for all v such that there is a directed edge (u -> v): dfs(v) \end{verbatim} Note that there may be different DFS orders for a given tree. Touko likes the present so much she decided to play with it! On each day following the wedding day, Touko performs this procedure once: - Among all directed edges $u \rightarrow v$ such that $a_u < a_v$, select the edge $u' \rightarrow v'$ with the lexicographically smallest pair $(a_{u'}, a_{v'})$. - Swap $a_{u'}$ and $a_{v'}$. Days have passed since their wedding, and Touko has somehow forgotten which date the wedding was and what was the original labeling $a$! Fearing that Yuu might get angry, Touko decided to ask you to derive these two pieces of information using the current labeling. Being her good friend, you need to find the number of days that have passed since the wedding, and the original labeling of the tree. However, there is a chance that Touko might have messed up her procedures, which result in the current labeling being impossible to obtain from some original labeling; in that case, please inform Touko as well.
From the structure, we see that until the end, the process is divided into $n$ phases, where the $i$-th involves phase pushing value $i$ from the root to the smallest-labeled leaf. Also in the following tutorial, I will use post-order and exit order, as well as pre-order and DFS order interchangeably. Lemma 1. After finishing pushing $i$, labels $1$ to $i$ are at the post-order positions, and the remaining labels from $i + 1$ to $n$ form the pre-order of the remaining part of the tree offsetted by $i$. Proof. There's a formal proof, but I think a better way is to show an illustration instead. After pushing $i$, we see that all green labels (label from $1$ to $i$) are at their post-order positions, while all red labels (labels from $i + 1$ to $n$) are connected and form the pre-order of the red subtree, with an offset of $i$. Moreover, this suggests that while pushing $i$, the label of the root is $i + 1$. Lemma 2. On any day, the order of the values of the children of any node stays the same. The proof will be left as an exercise for the reader, but a hint would be that for any node, a prefix of its children will be green nodes (nodes that have been pushed), the rest are red nodes (nodes that haven't been pushed). We can prove that the green nodes are ordered the same, the red nodes are ordered the same, and the green nodes are always less than the red nodes. Lemma 3. Suppose we are pushing/have just finished pushing $i$. Then the number of days that have passed is the sum of heights of all labels from $1$ to $i$. Proof. All labels that have finished being pushed, or are being pushed, have all traversed from the root down to their current position, which means the number of days to push each of these labels is equal to the height of the node containing the label. With the three lemmas, we can finally discuss the algorithm: First, we sort the children of each node by its value. Then we use this order to create the pre-order of the tree, and we can also figure out the current value that is being pushed (it is the value of the root minus 1). Call this value $v$. Knowing the current value being pushed, we first check if the current value is being pushed to the correct destination (i.e. check if the node with label $v$ is an ancestor of the node with post-order $v$). Then, we can "revert" the pushing of $v$ by swapping it back up the root, also taking to account the number of days. Finally, we check if values $< v$ are in the post-order positions, and values that are $\ge v$ form the pre-order shifted by $v - 1$ of the remaining of the tree. Complexity is $O(n \log n)$.
[ "brute force", "constructive algorithms", "data structures", "dfs and similar", "sortings", "trees" ]
3,100
null
1508
F
Optimal Encoding
Touko's favorite sequence of numbers is a permutation $a_1, a_2, \dots, a_n$ of $1, 2, \dots, n$, and she wants some collection of permutations that are similar to her favorite permutation. She has a collection of $q$ intervals of the form $[l_i, r_i]$ with $1 \le l_i \le r_i \le n$. To create permutations that are similar to her favorite permutation, she coined the following definition: - A permutation $b_1, b_2, \dots, b_n$ allows an interval $[l', r']$ to holds its shape if for any pair of integers $(x, y)$ such that $l' \le x < y \le r'$, we have $b_x < b_y$ if and only if $a_x < a_y$. - A permutation $b_1, b_2, \dots, b_n$ is $k$-similar if $b$ allows all intervals $[l_i, r_i]$ for all $1 \le i \le k$ to hold their shapes. Yuu wants to figure out all $k$-similar permutations for Touko, but it turns out this is a very hard task; instead, Yuu will encode the set of all $k$-similar permutations with directed acylic graphs (DAG). Yuu also coined the following definitions for herself: - A permutation $b_1, b_2, \dots, b_n$ satisfies a DAG $G'$ if for all edge $u \to v$ in $G'$, we must have $b_u < b_v$. - A $k$-encoding is a DAG $G_k$ on the set of vertices $1, 2, \dots, n$ such that a permutation $b_1, b_2, \dots, b_n$ satisfies $G_k$ if and only if $b$ is $k$-similar. Since Yuu is free today, she wants to figure out the minimum number of edges among all $k$-encodings for each $k$ from $1$ to $q$.
We will first solve the problem for $q$-similar permutations only. Let's transform each of the $q$ ranges into edges on a DAG we call $G$: for all ranges $[l_i, r_i]$, for all pairs of indices $l \le x, y \le r$ such that $a_x < a_y$, we add an edge from $x$ to $y$. We can easily see a permutation is $q$-similar iff it satisfies $G$. Now, our task is to remove edges from $G$ such that the number of permutations that satisfy it stays the same. Lemma 1. We can remove an edge $(u, v)$ if and only if there is a path from $u$ to $v$ with length $\ge 2$. Proof. If there exists a path of length $\ge 2$ between $(u, v)$, then we can remove the edge $(u, v)$ without having to worry about losing dependency between $u$ and $v$. On the other hand, if there doesn't exist such a path, then the only path connecting $u$ and $v$ is via the edge $(u, v)$ itself; removing that edge removes any dependency between $u$ and $v$. When that is the case, we can easily create a permutation such that $a_v = a_u + 1$, then we simply swap $a_u$ and $a_v$ to gain a permutation that does not satisfy the original DAG. Let's return to our problem. For any element $u$, we consider the edges connecting $u \to v$ such that $v > u$ a right edge of $u$; we define a left edge of $u$ in a similar manner. Lemma 2. There is at most one right edge of $u$. Proof. Suppose there are two right edges of $u$, namely $u \to w'$ and $u \to w$ (suppose $w' < w$). Because of our range construction, there must be a range that covers both $u$ and $w$. This range must covers $w'$ too, therefore there is a path between $w$ and $w'$, therefore we can remove either $u \to w$ or $u \to w'$. Therefore, there is at most one right edge $u \to u_r$. We can actually find this right edge: suppose $[l, r]$ is a range such that $l \le u \le r$, and $r$ is as large as possible. Then $u_r$ is the index between $u$ and $r$ such that $a_{u_r} > a_u$ and $a_{u_r}$ is as small as possible. We can prove similar results with the left edge of $u$ (denoted as $u \to u_l$). However, there will be cases when $u \to u_r$ is actually not needed (I will call this phenomenon being hidden). What is the condition for $u \to u_r$ to be hidden? That's when there's a path from $u$ to $u_r$ with length $\ge 2$! Suppose this path is in the format $u \to \dots \to t \to u_r$. We can prove that $t < u$: if $t > u$ then that implies $a_t > a_u$ but $a_t < a_{u_r}$, which means the right edge of $u$ is $u \to t$ instead. Because $t < u$, we can take the range $[l, r]$ such that $l \le u_r \le r$, $l$ is as small as possible, and check if there exists an index $t \in [l, u]$ such that $a_u < a_t < a_w$. That concludes the solution for finding the optimal encoding for $q$-permutations. To recap: Find left and right edges of all $u$. Check if the left/right edges of all $u$ are hidden. If they are, remove them from the answer. Let's return to the original problem. For each range $[l_i, r_i]$, instead of adding an edge for every $l \le x, y \le r$ to $G$, let's only add an edge between $x'$ and $y'$ such that $a_{x'}$ and $a_{y'}$ are adjacent values in the range. This doesn't change our answer because of lemma 1. Let's call these edges candidate edges. Surprisingly, all of our previous observations hold, but this time on the set of candidate edges. Namely, At any query, there is at most one right edge $u \to u_r$, which is one of the candidate edges. The right edge $u \to u_r$ must satisfy that $u_r > u$, $a_{u_r} < a_u$ and $a_{u_r}$ is the smallest such value in the range $[u, r]$, where $[l, r]$ is the range covering $u$ with the largest $r$. $u \to u_r$ is hidden if there exists a candidate edge $u \to t$ such that $t < u$, $a_u < a_t < a_{u_r}$, and $t \in [l, u]$ where $[l, r]$ is the range covering $u_r$ with the smallest $l$. We call this edge $u \to t$ the destroyer of the edge $u \to u_r$. All of the above points holds for the left edge $u \to u_l$. Let's organize the candidate edges: for any edge $u \to v$, if $v > u$, label $u \to v$ as a right candidate edge of $u$, else label $u$ as a left candidate edge of $u$. Let's sort the right candidate edges of $u$ by increasing $u_r$, and sort the left candidate edges of $u$ by decreasing $u_l$. Observation. The values of the right end of the right candidate edges are decreasing, i.e. if the right candidate edges of $u$ are $u \to u_{r,1}, u \to u_{r,2}, ..., u \to u_{r,k}$ such that, $u_{r,1} < u_{r,2} < \dots < u_{r,k}$, then $a_{u_{r,1}} > a_{u_{r,2}} > \dots > a_{u_{r,k}}$. Similarly, if we sort the left candidate edges of $u$ by decreasing index, then the values of the left end of these candidate edges are decreasing. Using this observation, we can prove that if the destroyer of $u \to u_{r_i}$ is $u \to u_{l_j}$, and the destroyer of $u \to u_{r_{i + 1}}$ is $u \to u \to u_{l, k}$, then $u_{l, j} \ge u_{l, k}$, or $j \le k$; we can also prove a similar result with the destroyers of left candidate edges. Therefore, we can use two pointers to figure out the destroyer for each left and right candidate edge of $u$. For each right candidate edge $[u \to u_{r,i}]$, let's see when this candidate edge is used in the optimal encoding: The candidate edge is first activated when there exists a range covering $[u, u_{r, i}]$. We call this timestamp $t_1$. The candidate edge is hidden when there exists a range covering $[u_{l, j}, u_{r,i}]$, where $u \to u_{l,j}$ is the destroyer of $u \to u_{r,i}$. We call this timestamp $t_2$. The candidate edge is deactivated when there exists a range covering $[u, u_{r, i + 1}]$, where $u \to u_{r, i + 1}$ is the right candidate edge after $u \to u_{r,i}$. We call this timestamp $t_3$. For each candidate edge, we can find these timestamps using a Fenwick tree. With these three timestamps, we can figure out the range of time where each candidate edge is used (which is $[t_1, \min(t_2, t_3))$), and modify the answer accordingly. Finally, let's find out how many candidate edges there are: Lemma 3. The number of candidate edges is $O(n \sqrt{q})$. Proof. Suppose for a range $[l, r]$, we maintain edges $u \to v$ such that $l \le u, v \le r$, and the values $a_u$ and $a_v$ are adjacent in the range $[l, r]$. When we add/subtract one of the ends by 1, i.e. when we consider $[l \pm 1, r \pm 1]$, the amount of edges that are modified between $[l, r]$ and $[l \pm 1, r \pm 1]$ is $O(1)$ (for example, if we add another element, then we remove at most 1 old edge and add at most 2 new edges; similarly, when removing an element, we remove at most 2 old edges and add at most 1 new edge). Therefore, consider Mo's algorithm on the given collection of ranges $[l_i, r_i]$, each candidate edge must appear during the process of iterating over the ranges, and the number of modification is $O(n \sqrt{q})$, therefore the number of candidate edges is $O(n \sqrt{q})$. That concludes the solution to the full problem. To recap: Find all candidate edges. Find the destroyer of all candidate edges. Find the range of timestamps where each candidate edge is used. The complexity is $O(n \sqrt{q} \log n)$. Notes. In particular, your set candidate edges does not have to be exactly the edges connecting consecutive values between ranges; these candidate edges only need to satisfy 3 conditions: All edges that are included in some optimal $k$-encoding must be present in the set of candidate edges. The observation is not violated, i.e. if we sort the left/right candidate edges of any node $u$ by the other endpoint, then the value at the other endpoint must be sorted as well. The number of candidate edges must not be too large, at about $O(n \sqrt{q})$ edges. This is to loosen up the process of generating the candidate edges, since the naive Mo-and-set-of-values approach is incredibly expensive. My edge-generating approach involves using Mo with rollback to only allow deletion of values so I can maintain the sorted values with a linked list, and I also do not delete intermediary edges while iterating one range to another.
[ "brute force", "data structures" ]
3,500
#include <bits/stdc++.h> using namespace std; using namespace chrono; const int N = 25005, Q = 100005, D = 80; int n, q, a[N], l[Q], r[Q], pos[N], ans[Q]; set<int> se; vector<pair<int, int>> edges; vector<int> in, out; vector<pair<int, int>> l_edge[N], r_edge[N]; vector<array<int, 3>> eve[N]; vector<pair<int, int>> add[N]; vector<pair<int, int>> cur, fin; struct fenwick_tree { int bit[N]; void init() { fill(bit + 1, bit + n + 1, Q); } void update(int u, int v) { for (; u > 0; u -= u & -u) { bit[u] = min(bit[u], v); } } int query(int u) { int ans = Q; for (; u <= n; u += u & -u) { ans = min(ans, bit[u]); } return ans; } } bit; void find_all_edges() { auto add_node = [&](int u) { auto it = se.insert(u).first; if (it != se.begin()) { cur.push_back({*prev(it), u}); } if (next(it) != se.end()) { cur.push_back({u, *next(it)}); } }; auto remove_node = [&](int u) { se.erase(u); auto it = se.lower_bound(u); if (it != se.end() && it != se.begin()) { cur.push_back({*prev(it), *it}); } }; auto flush_pair = [&]() { for (auto [u, v] : cur) { fin.push_back({u, v}); } cur.clear(); }; vector<int> que; for (int i = 1; i <= q; i++) { que.push_back(i); } sort(que.begin(), que.end(), [](const int u, const int v) { return l[u] / D != l[v] / D ? l[u] < l[v] : r[u] < r[v]; }); int le = 1, ri = 0; for (int ind : que) { int cl = l[ind], cr = r[ind]; while (ri < cr) { add_node(a[++ri]); } while (le > cl) { add_node(a[--le]); } while (ri > cr) { remove_node(a[ri--]); } while (le < cl) { remove_node(a[le++]); } flush_pair(); } edges = vector<pair<int, int>>(fin.begin(), fin.end()); sort(edges.begin(), edges.end()); edges.erase(unique(edges.begin(), edges.end()), edges.end()); in = vector<int>(edges.size(), Q - 1); out = vector<int>(edges.size(), Q - 1); } void build_events() { for (int i = 0; i < edges.size(); i++) { auto [u, v] = edges[i]; int iu = pos[u], iv = pos[v]; (iv > iu ? r_edge : l_edge)[iu].push_back({iv, i}); } for (int i = 1; i <= n; i++) { vector<pair<int, int>> &le = l_edge[i], &re = r_edge[i]; reverse(le.begin(), le.end()); reverse(re.begin(), re.end()); le.push_back({0, -1}); re.push_back({n + 1, -1}); int pl = 0, pr = 0; while (pl < le.size() - 1 || pr < re.size() - 1) { if (a[le[pl].first] > a[re[pr].first]) { int qi = le[pl].second; int u = i, v = le[pl].first; // (edge u => v, go to left) int t = re[pr].first; int vn = le[pl + 1].first; eve[v].push_back({u, qi, 0}); eve[vn].push_back({u, qi, 1}); eve[v].push_back({t, qi, 1}); pl++; } else { int qi = re[pr].second; int u = i, w = re[pr].first; // (edge u => w, go to right) int t = le[pl].first; int wn = re[pr + 1].first; eve[u].push_back({w, qi, 0}); eve[t].push_back({w, qi, 1}); eve[u].push_back({wn, qi, 1}); pr++; } } } for (int i = 1; i <= q; i++) { add[l[i]].push_back({r[i], i}); } } void solve() { bit.init(); for (int i = 1; i <= n; i++) { for (auto [r, v] : add[i]) { bit.update(r, v); } for (auto [r, i, t] : eve[i]) { int &upd = (t == 0 ? in[i] : out[i]); upd = min(upd, bit.query(r)); } } for (int i = 0; i < edges.size(); i++) { ans[in[i]]++; ans[out[i]]--; } for (int i = 1; i <= q; i++) { ans[i] += ans[i - 1]; cout << ans[i] << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> q; for (int i = 1; i <= n; i++) { cin >> a[i]; pos[a[i]] = i; } for (int i = 1; i <= q; i++) { cin >> l[i] >> r[i]; } find_all_edges(); build_events(); solve(); }
1509
A
Average Height
Sayaka Saeki is a member of the student council, which has $n$ other members (excluding Sayaka). The $i$-th member has a height of $a_i$ millimeters. It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is \textbf{as large as possible}. A pair of two consecutive members $u$ and $v$ on a line is considered photogenic if their average height is an integer, i.e. $\frac{a_u + a_v}{2}$ is an integer. Help Sayaka arrange the other members to \textbf{maximize} the number of photogenic consecutive pairs.
For two consecutive members to be non-photogenic, $a_u$ and $a_v$ must have different parity. Therefore, to maximize the number of photogenic pairs, or to minimize the number of non-photogenic pairs, we will order the members so that all members with even height are in front and all members with odd height are at the back.
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t, n; cin >> t; while (t--) { cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } partition(a.begin(), a.end(), [&](const int u) { return u % 2; }); for (int i = 0; i < n; i++) { cout << a[i] << " \n"[i == n - 1]; } } }
1509
B
TMT Document
The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it. However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $n$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences. A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) characters.
There are many slightly different solutions, all based on some sort of greedy idea. Write $n = 3k$ for convenience. Obviously, the string must have $k$ characters M and $2k$ characters T for the partition to be possible, so we can just discard all other cases. Now, let's consider the first M character in the string. This must be part of some TMT subsequence, so we must choose a T character to its left to work as the first character of this subsequence. Which character should we choose? Well, it seems intuitive to match it with the first T character we find going from left to right - it is certainly not the right character of any sequence, and it seems like a good idea to assign it to the first M character since characters that are further to the right may be too far right to match with this character. Continuing this idea, we come up with the following greedy algorithm: Take the first $k$ T characters and use them as the first characters of the subsequences, matching them with the $k$ M characters from left to right greedily. Similarly, take the last $k$ T characters and match them with each M character from left to right greedily. If either of these steps fails, the partition is impossible. This can be formalized into the following observation, which is both easy to prove and gives a solution that is very easy to implement. Claim. Let $m_1 < m_2 < \dots < m_k$ be the positions of the M characters and let $t_1 < t_2 < \dots < t_{2k}$ be the positions of the T characters. Then the partition exists if and only if $t_i < m_i < t_{i + k}$ for $1 \le i \le k$. Proof. If the condition holds then we can just choose the $k$ subsequences with indices $(t_i, m_i, t_{i + k})$, so it is sufficient. To see that it's necessary, consider the first $i$ M characters with indices $m_1, m_2, \dots, m_i$, and consider the left T characters in the subsequence they're in. These are to the left of their corresponding M characters, and in particular they are to the left of the $i$-th M character. Thus there's at least $i$ T characters to the left of the $i$-th M character, meaning $t_i < m_i$. The other inequality is proved similarly. Do yourself a favor and listen to Towa-sama's singing! Here are some links to cool songs.
[ "greedy" ]
1,100
#include <bits/stdc++.h> using namespace std; bool solve() { int n; cin >> n; string s; cin >> s; vector<int> t, m; for(int i = 0; i < n; i++) { if(s[i] == 'T') t.push_back(i); else m.push_back(i); } if(t.size() != 2 * m.size()) return false; for(int i = 0; i < m.size(); i++) { if(m[i] < t[i] || m[i] > t[i + m.size()]) return false; } return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { cout << (solve() ? "YES" : "NO") << '\n'; } }
1509
C
The Sports Festival
The student council is preparing for the relay race at the sports festival. The council consists of $n$ members. They will run one after the other in the race, the speed of member $i$ is $s_i$. The discrepancy $d_i$ of the $i$-th stage is the difference between the maximum and the minimum running speed among the first $i$ members who ran. Formally, if $a_i$ denotes the speed of the $i$-th member who participated in the race, then $d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$. You want to minimize the sum of the discrepancies $d_1 + d_2 + \dots + d_n$. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?
Assume that the array of speeds is sorted, i.e. $s_1 \le s_2 \le \dots \le s_n$. The key observation is that the last running can be assumed to be either $s_1$ or $s_n$. This is because if $s_1$ and $s_n$ are both in the prefix of length $i$, then clearly $d_i = s_n - s_1$, which is the maximum possible value of any discrepancy. Similarly $d_{i + 1}, d_{i + 2}, \dots, d_n$ are all equal to $s_n - s_1$. This moving either $s_1$ or $s_n$ (whichever appears last) to the very end of the array cannot possibly increase the sum of these discrepancies, since they already have the largest possible value. If we repeat the previous observation, we deduce that for each $i$, the prefix of length $i$ in an optimal solution forms a contiguous subarray of the sorted array. Therefore, we may solve the problem through dynamic programming: $dp(l, r)$ represents the minimum possible answer if we solve for the subarray $s[l \dots r]$. Clearly $dp(x, x) = 0$, and the transition is given by $dp(l, r) = s_r - s_l + \min(dp(l + 1, r), dp(l, r - 1))$ Which corresponds to placing either the smallest or the largest element at the end of the sequence. The final answer is $dp(1, n)$. This allows us to solve the problem in $O(n^2)$. This problem was originally going to appear in Codeforces Round 668 (Div. 2), but it was removed one day before the contest for balance reasons :P
[ "dp", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; using ll = long long; const int MAX = 2e3 + 5; ll mem[MAX][MAX], a[MAX]; ll dp(int l, int r) { if(mem[l][r] != -1) return mem[l][r]; if(l == r) return 0; return mem[l][r] = a[r] - a[l] + min(dp(l + 1, r), dp(l, r - 1)); } int main() { int n; cin >> n; for(int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); memset(mem, -1, sizeof mem); cout << dp(0, n - 1) << '\n'; }
1511
A
Review Site
You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote. However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes. $n$ reviewers enter the site one by one. Each reviewer is one of the following types: - type $1$: a reviewer has watched the movie, and they like it — they press the upvote button; - type $2$: a reviewer has watched the movie, and they dislike it — they press the downvote button; - type $3$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once. Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one. What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?
Notice that the answer depends only on the number of the reviewers of the third type who upvote the movie. Optimally we would want every single reviewer of the third type to upvote. We can achieve it with the following construction: send all reviewers of the first type to the first server, all reviewers of the second type to the second server and all reviewers of the third type to the first server. Since there are no downvotes on the first server, all reviewers of the third type will upvote. Thus, the answer is the total number of reviewers of the first and the third type. Overall complexity: $O(n)$ per testcase.
[ "greedy" ]
800
fun main() { repeat(readLine()!!.toInt()) { readLine()!!.toInt() println(readLine()!!.split(' ').count { it != "2" }) } }
1511
B
GCD Length
You are given three integers $a$, $b$ and $c$. Find two positive integers $x$ and $y$ ($x > 0$, $y > 0$) such that: - the decimal representation of $x$ without leading zeroes consists of $a$ digits; - the decimal representation of $y$ without leading zeroes consists of $b$ digits; - the decimal representation of $gcd(x, y)$ without leading zeroes consists of $c$ digits. $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. Output $x$ and $y$. If there are multiple answers, output any of them.
The easiest way to force some gcd to be of some fixed length is to use the divisibility rules for $2$, $5$ or $10$: if the number produced by the last $y$ digits $x$ is divisible by $2^y$, then $x$ is also divisible by $2^y$ (same goes for $5^y$ and $10^y$). One of the possible constructions is the following: let $x=1\underbrace{0..0}_{a-c}\underbrace{0..0}_{c-1}$ and $y=1\underbrace{1..1}_{b-c}\underbrace{0..0}_{c-1}$. Since $10..0$ and $11..1$ are pairwise prime, gcd is $10^{c-1}$. Overall complexity: $O(1)$ per testcase.
[ "constructive algorithms", "math", "number theory" ]
1,100
for t in range(int(input())): a, b, c = map(int, input().split()) print("1" + "0" * (a - 1), "1" * (b - c + 1) + "0" * (c - 1))
1511
C
Yet Another Card Deck
You have a card deck of $n$ cards, numbered from top to bottom, i. e. the top card has index $1$ and bottom card — index $n$. Each card has its color: the $i$-th card has color $a_i$. You should process $q$ queries. The $j$-th query is described by integer $t_j$. For each query you should: - find the highest card in the deck with color $t_j$, i. e. the card with minimum index; - print the position of the card you found; - take the card and place it on top of the deck.
Let's look at one fixed color. When we search a card of such color, we take the card with minimum index and after we place it on the top of the deck it remains the one with minimum index. It means that for each color we take and move the same card - one card for each color. In other words, we need to keep track of only $k$ cards, where $k$ is the number of colors ($k \le 50$). As a result, if $pos_c$ is the position of a card of color $c$ then we can simulate a query in the following way: for each color $c$ such that $pos_c < pos_{t_j}$ we increase $pos_c$ by one (since the card will move down) and then set $pos_{t_j} = 1$. Complexity is $O(n + qk)$. But, if we look closely, we may note that we don't even need array $pos_c$. We can almost manually find the first card of color $t_j$ and move it to the first position either by series of swaps or, for example, using rotate function (present in C++) and it will work fast. Why? Let's look at one color $c$. For the first time it will cost $O(n)$ operations to search the corresponding card and move it to the position $1$. But after that, at any moment of time, the position of the card won't exceed $k$, since all cards before are pairwise different (due to the nature of queries). So, all next moves the color $c$ costs only $O(k)$ time. As a result, the complexity of such almost naive solution is $O(kn + qk)$.
[ "brute force", "data structures", "implementation", "trees" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int n, q; scanf("%d%d", &n, &q); vector<int> a(n); for (int& x : a) scanf("%d", &x); while (q--) { int x; scanf("%d", &x); int p = find(a.begin(), a.end(), x) - a.begin(); printf("%d ", p + 1); rotate(a.begin(), a.begin() + p, a.begin() + p + 1); } }
1511
D
Min Cost String
Let's define the cost of a string $s$ as the number of index pairs $i$ and $j$ ($1 \le i < j < |s|$) such that $s_i = s_j$ and $s_{i+1} = s_{j+1}$. You are given two positive integers $n$ and $k$. Among all strings with length $n$ that contain only the first $k$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.
Consider all possible strings of length $2$ on the alphabet of size $k$ (there are $k^2$ of them). Let $cnt_i$ be the number of occurrences of the $i$-th of them in the string $s$. The cost of the string $s$ by definition is $\sum \limits_{i} \frac{cnt_i(cnt_i - 1)}{2}$. Now, let's suppose there are two strings $i$ and $j$ such that $cnt_i - cnt_j \ge 2$. Then, if we somehow reduce the number of occurrences of the string $i$ by $1$ and increase the number of occurrences of the string $j$ by $1$, the cost will decrease. So, in the optimal answer all the strings of length $2$ should appear the same number of times (and if it's impossible, the difference in the number of appearances should not be greater than $1$). Let's suppose that $k^2 = n - 1$, then our goal is to build a string where each string of length $2$ on the alphabet of $k$ characters appears exactly once. The construction of this string can be modeled using Eulerian cycles: build a directed graph with $k$ vertices, where each vertex represents a character, each arc represents a string of length $2$, and for every pair of vertices $(i, j)$, there is an arc from $i$ to $j$ (it's possible that $i = j$!). Then, by finding the Eulerian cycle in this graph (it always exists since the graph is strongly connected and, for each vertex, its in-degree is equal to its out-degree), we find a string of length $k^2 + 1$ such that all its substrings are different (so each string of length $2$ appears there once as a substring). Okay, what about the cases $k^2 > n - 1$ and $k^2 < n - 1$? Since the string we build for the case $k^2 = n - 1$ represents a cycle, we can make it "cyclical" and repeat the required number of times, then cut last several characters if it's too big. For example, if $n = 8$, $k = 2$, then the string for $k = 2$ is abbaa (it's not the only one, but we can use it). We can expand this string to abbaabbaa (by repeating the last $k^2$ characters), and delete the last character so its length is $8$. By the way, in this problem, you don't have to implement the algorithm that finds Eulerian cycles. The graph where we want to find the Eulerian cycle has a very special structure, and there are many different constructive ways to find the cycle in it. But if you can't use them, you always can rely on the straightforward solution that explicitly searches for the Eulerian cycle.
[ "brute force", "constructive algorithms", "graphs", "greedy", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; int n, k; int cur[26]; vector<int> path; void dfs(int v) { while (cur[v] < k) { int u = cur[v]++; dfs(u); path.push_back(u); } } int main() { scanf("%d%d", &n, &k); dfs(0); printf("a"); for (int i = 0; i < n - 1; ++i) printf("%c", path[i % path.size()] + 'a'); }
1511
E
Colorings and Dominoes
You have a large rectangular board which is divided into $n \times m$ cells (the board has $n$ rows and $m$ columns). Each cell is either white or black. You paint each white cell either red or blue. Obviously, the number of different ways to paint them is $2^w$, where $w$ is the number of white cells. After painting the white cells of the board, you want to place the maximum number of dominoes on it, according to the following rules: - each domino covers two adjacent cells; - each cell is covered by at most one domino; - if a domino is placed horizontally (it covers two adjacent cells in one of the rows), it should cover only red cells; - if a domino is placed vertically (it covers two adjacent cells in one of the columns), it should cover only blue cells. Let the value of the board be the maximum number of dominoes you can place. Calculate the sum of values of the board over all $2^w$ possible ways to paint it. Since it can be huge, print it modulo $998\,244\,353$.
There are different solutions to this problem involving combinatorics and/or dynamic programming, but, in my opinion, it's a bit easier to look at the problem from the perspective of probability theory. Let's suppose a coloring is already chosen. Then it can be covered with dominoes greedily: red and blue cells are independent from each other, and, for example, red cells can be analyzed as a set of "strips" of them of different length. Let's say that we cover each "strip" from left to right, so, in each "strip", the first domino covers the cells $1$ and $2$, the second domino - the cells $3$ and $4$, and so on. Let's calculate the average value of the coloring, that is, the expected value of the coloring if it is chosen randomly. Let it be $E$, then the answer is $2^w E$. By linearity of expectation, $E$ can be calculated as $\sum\limits_{d \in D} p_d$, where $D$ is the set of all places we can use for a domino, and $p_d$ is the probability that there is a domino in place $d$ in our domino covering (which we construct greedily). Each domino covers two adjacent cells, so we can iterate on pairs of adjacent cells, and for each pair, find the probability that this pair is covered. Let's suppose that we want to cover the cells $(x, y)$ and $(x, y + 1)$ with a domino. Then: both of these cells should be red; the length of the red "strip" before these cells should be even (otherwise the cell $(x, y)$ will be paired with the cell $(x, y - 1)$). The only thing we need to know in order to calculate the probability of these two conditions being true is the number of white cells before the cell $(x, y)$ - which can be easily maintained. Knowing the number of white cells before $(x, y)$, we can either use dynamic programming to calculate the required probability, or do the math on several easy examples and try to notice the pattern: if there are $0$ white cells before the current one, the probability of that pair being covered with a domino (let's call it $P_0$) is $\frac{1}{4}$ (both these cells should be red); if there is $1$ white cell before the current one, the probability of that pair being covered with a domino (let's call it $P_1$) is $\frac{1}{4} - \frac{1}{8}$ (the cells $(x, y)$ and $(x, y + 1)$ should be red, but the cell before them should not be red); $P_2$ is $\frac{1}{4} - \frac{1}{8} + \frac{1}{16}$ (either the chosen two cells are red and the cell before them is not red, or all four cells are red); $P_3$ is $\frac{1}{4} - \frac{1}{8} + \frac{1}{16} - \frac{1}{32}$, and so on. So, knowing the number of white cells before $(x, y)$ and $(x, y + 1)$, we easily calculate the probability of this pair being covered by a domino. By summing up the probabilities over all pairs of adjacent white cells (don't forget the vertical ones!), we get the average (or expected) value of the coloring. All that's left is to multiply it by $2^w$.
[ "combinatorics", "dp", "greedy", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 300043; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, MOD - y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y > 0) { if(y % 2 == 1) z = mul(z, x); x = mul(x, x); y /= 2; } return z; } int inv(int x) { return binpow(x, MOD - 2); } int divide(int x, int y) { return mul(x, inv(y)); } string s[N]; int p[N]; int n, m; char buf[N]; int main() { scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) { scanf("%s", buf); s[i] = buf; } p[0] = divide(1, 2); for(int i = 1; i < N; i++) if(i % 2 == 1) p[i] = sub(p[i - 1], divide(1, binpow(2, i))); else p[i] = add(p[i - 1], divide(1, binpow(2, i))); int ans = 0; int w = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(s[i][j] != '*') w = add(w, 1); for(int i = 0; i < n; i++) { int c = 0; for(int j = 0; j < m; j++) { if(s[i][j] == '*') c = 0; else c++; if(c > 0) ans = add(ans, p[c]); } } for(int j = 0; j < m; j++) { int c = 0; for(int i = 0; i < n; i++) { if(s[i][j] == '*') c = 0; else c++; if(c > 0) ans = add(ans, p[c]); } } ans = mul(ans, binpow(2, w)); cout << ans << endl; }
1511
F
Chainword
A chainword is a special type of crossword. As most of the crosswords do, it has cells that you put the letters in and some sort of hints to what these letters should be. The letter cells in a chainword are put in a single row. We will consider chainwords of length $m$ in this task. A hint to a chainword is a sequence of segments such that the segments don't intersect with each other and cover all $m$ letter cells. Each segment contains a description of the word in the corresponding cells. The twist is that there are actually two hints: one sequence is the row above the letter cells and the other sequence is the row below the letter cells. When the sequences are different, they provide a way to resolve the ambiguity in the answers. You are provided with a dictionary of $n$ words, each word consists of lowercase Latin letters. All words are pairwise distinct. An instance of a chainword is the following triple: - a string of $m$ lowercase Latin letters; - the first hint: a sequence of segments such that the letters that correspond to each segment spell a word from the dictionary; - the second hint: another sequence of segments such that the letters that correspond to each segment spell a word from the dictionary. Note that the sequences of segments don't necessarily have to be distinct. Two instances of chainwords are considered different if they have different strings, different first hints \textbf{or} different second hints. Count the number of different instances of chainwords. Since the number might be pretty large, output it modulo $998\,244\,353$.
Let's use a trie to store the given words. Now let's imagine a procedure that checks if some string of length $m$ can be represented as a concatenation of some of these words. If the words were prefix-independent - no word was a prefix of another word, that task would be solvable with a greedy algorithm. We could iterate over a string and maintain the current vertex of the trie we are in. Append a current letter. If there is no such transition in a trie, it can't be represented. If the vertex we go to is a terminal, jump to the root of the trie. Otherwise, just go to that vertex. However, since the words aren't prefix-independent, we have a terminal on a path to other terminals. Thus, we can't immediately decide if we should jump to the root or just go. Let's handle this with dynamic programming. $dp[i][v]$ - can we put $i$ letters in such a way that the vertex of a trie we are in is $v$. Is building a chainword letter by letter that different from this process? Apparently, it isn't. Consider $dp[i][v][u]$ - how many ways are there to put $i$ letters in a string so that the first hint is in a vertex $v$ and the second hint is in a vertex $u$. For the transition we can try all $26$ letters to put and jump to the corresponding vertices. That obviously, is too slow. The intuition tells us that this dp should be calculated with some kind of matrix exponentiation (since $m \le 10^9$). That dp can be rewritten as a matrix pretty easily. However, its size is up to $1681 \times 1681$ (the maximum number of vertices in a trie squared). Some say that there is a way to compute the $m$-th power of such a huge matrix fast enough with Berlekamp-Massey, but I unfortunately am not familiar with it. Thus, we'll have to reduce the size of our matrix. First, notice that the only reachable states $(v, u)$ are such that the word that is written on a path from the root to $v$ is a suffix of a word that is written on a path from the root to $u$ or vice versa. Look at it the other way: if we build a trie on the reversed words, then one of the vertices will be an ancestor of another one. Now it's easy to estimate the number of states as the sum of depths of all vertices. However, since we look at ordered pairs of $(v, u)$, we should more or less double that amount. That should be $241$ states at max. This can probably pass with an optimal enough implementation. We can do better, though. Let's merge the states $(v, u)$ and $(u, v)$ into one state. The intuition is basically that you can swap the hints at will. That makes the pairs unordered: now there are up to $161$ pairs. That surely will work fast enough. The way to generate all the possible states is the following: run a dfs/bfs, starting from $(0, 0)$ that makes all valid transition and record all the states that can be visited. While preparing the tests, I only managed to get up to $102$ states and I would really love to hear an approach to either prove a tighter bound or to generate a test closer to the bound of $161$.
[ "brute force", "data structures", "dp", "matrices", "string suffix structures", "strings" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; const int K = 161; const int AL = 26; struct node{ int nxt[AL]; bool term; node(){ memset(nxt, -1, sizeof(nxt)); term = false; }; int& operator [](const int x){ return nxt[x]; } }; vector<node> trie; int tot; void add(const string &s){ int cur = 0; int d = 1; for (const char &c : s){ ++d; if (trie[cur][c - 'a'] == -1){ trie[cur][c - 'a'] = trie.size(); trie.push_back(node()); tot += d; } cur = trie[cur][c - 'a']; } trie[cur].term = true; } int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } typedef array<array<int, K>, K> mat; mat operator *(const mat &a, const mat &b){ mat c; forn(i, K) forn(j, K) c[i][j] = 0; forn(i, K) forn(j, K) forn(k, K) c[i][j] = add(c[i][j], mul(a[i][k], b[k][j])); return c; } mat binpow(mat a, long long b){ mat res; forn(i, K) forn(j, K) res[i][j] = i == j; while (b){ if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } map<pair<int, int>, int> num; queue<pair<int, int>> q; int get(int v, int u){ if (v > u) swap(v, u); if (!num.count({v, u})){ int k = num.size(); assert(k < K); num[{v, u}] = k; q.push({v, u}); } return num[{v, u}]; } int main() { int n; long long m; cin >> n >> m; trie = vector<node>(1, node()); tot = 1; forn(i, n){ string s; cin >> s; add(s); } q.push({0, 0}); num[q.front()] = 0; mat init; forn(i, K) forn(j, K) init[i][j] = 0; while (!q.empty()){ int v = q.front().first; int u = q.front().second; q.pop(); int x = get(v, u); forn(c, AL){ int tov = trie[v][c]; int tou = trie[u][c]; if (tov == -1 || tou == -1) continue; ++init[x][get(tov, tou)]; if (trie[tov].term) ++init[x][get(0, tou)]; if (trie[tou].term) ++init[x][get(tov, 0)]; if (trie[tov].term && trie[tou].term) ++init[x][0]; } } init = binpow(init, m); printf("%d\n", init[0][0]); return 0; }
1511
G
Chips on a Board
Alice and Bob have a rectangular board consisting of $n$ rows and $m$ columns. \textbf{Each row contains exactly one chip.} Alice and Bob play the following game. They choose two integers $l$ and $r$ such that $1 \le l \le r \le m$ and cut the board in such a way that only the part of it between column $l$ and column $r$ (inclusive) remains. So, all columns to the left of column $l$ and all columns to the right of column $r$ no longer belong to the board. After cutting the board, they move chips on the remaining part of the board (the part from column $l$ to column $r$). They make alternating moves, and the player which cannot make a move loses the game. The first move is made by Alice, the second — by Bob, the third — by Alice, and so on. During their move, the player must choose one of the chips from the board and move it any positive number of cells to the left (so, if the chip was in column $i$, it can move to any column $j < i$, and the chips in the leftmost column cannot be chosen). Alice and Bob have $q$ pairs of numbers $L_i$ and $R_i$. For each such pair, they want to determine who will be the winner of the game if $l = L_i$ and $r = R_i$. Note that these games should be considered independently (they don't affect the state of the board for the next games), and both Alice and Bob play optimally.
The model solution is $O(N \sqrt{N \log N})$, where $N = \max(n, m, q)$, but it seems that there are faster ones. I'll explain the model solution nevertheless. It's easy to see (using simple Nim theory) that the answer for a query $i$ is B iff the xor of $c_j - L_i$ for all chips such that $L_i \le c_j \le R_i$ is equal to $0$. Let's calculate this xor for every query. This number contains at most $18$ bits, and we will process these bits differently: we will choose some number $K$ and use one solution to calculate $K$ lowest bits, and another solution to compute $18 - K$ highest bits. One idea is common in both solutions: we split each query into two queries - a query $(L_i, R_i)$ can be represented as a combination of two queries $Q(L_i, L_i)$ and $Q(R_i + 1, L_i)$, where $Q(x, y)$ is the xor of all numbers $c_j - y$ such that $c_j \ge x$. After converting the queries, for every $x \in [1, m]$, store each query of the form $Q(x, y)$ in some sort of vector (or any other data structure). We will use an approach similar to sweep line: iterate on $x$ and solve the queries for the current $x$. These ideas will be used both for the solution calculating $K$ lowest bits and for the solution calculating $18 - K$ highest bits. How to find $K$ lowest bits in each query? Iterate on $x$ from $m$ to $1$ and maintain the number of occurrences of each number $c_i$ we met so far. Then, at a moment we want to calculate $Q(x, y)$, simply iterate on all of the values of $c_i$ and process each value in $O(1)$ (if the number of occurrences of some value $z$ is odd, update the current answer to the query by xoring the number with $z - y$, otherwise just skip it). And since we are interested only in $K$ lowest bits, for each $c_i$, we need only the remainder $c_i \mod 2^K$, so the number of different values is $O(2^K)$. Thus, this part of the solution runs in $O(n + m + 2^Kq)$. Okay, what about $18 - K$ highest bits in each query? We can see that, for every number $c_i$, the highest bits of $c_i - x$ don't change too often when we iterate on $x$: there will be about $\frac{m}{2^K}$ segments where the highest bits of $c_i - x$ have different values. We can build a data structure that allows use to process two queries: xor all numbers on a segment with some value and get the value in some position (Fenwick trees and segment trees can do it). Then, we again iterate on $x$ from $m$ to $1$. When we want to process a number $c_i$, we find the segments where the highest bits of $c_i - x$ have the same value and perform updates on these segments in our data structure. When we process a query of the form $Q(x, y)$, we simply get the value in the position $y$ from our data structure. This part of the solution works in $O(n \frac{m}{2^K} \log m + m + q)$. By choosing $K$ optimally, we can combine these two parts into a solution with complexity of $O(N \sqrt{N \log N})$.
[ "bitmasks", "brute force", "data structures", "dp", "games", "two pointers" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 200043; const int K = 10; const int Z = 1 << K; int rem[Z]; int t[N]; int get(int r) { int result = 0; for (; r >= 0; r = (r & (r + 1)) - 1) result ^= t[r]; return result; } void change(int i, int delta) { for (; i < N; i = (i | (i + 1))) t[i] ^= delta; } int get(int l, int r) { return get(r) - get(l - 1); } int ans[N]; int c[N]; int cnt[N]; int n, m; int ls[N]; int rs[N]; vector<int> qs[N]; vector<int> qs2[N]; int main() { scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) { scanf("%d", &c[i]); cnt[c[i]]++; } int q; scanf("%d", &q); for(int i = 0; i < q; i++) { int l, r; scanf("%d %d", &l, &r); ls[i] = l; rs[i] = r; qs[l].push_back(i); qs2[r + 1].push_back(i); } for(int i = m; i >= 1; i--) { for(int j = 0; j < cnt[i]; j++) { rem[i % (1 << K)]++; int r = i; while(true) { int l = r - Z + 1; l = max(1, l); if(l > r) break; int diff = i - l; diff >>= K; change(l, diff); change(r + 1, diff); r -= Z; } } for(auto x : qs[i]) { int cur = (get(i)) << K; for(int k = 0; k < Z; k++) { int dist = (k - i) % Z; if(dist < 0) dist += Z; if(rem[k] & 1) cur ^= dist; } ans[x] ^= cur; } for(auto x : qs2[i]) { int cur = (get(ls[x])) << K; for(int k = 0; k < Z; k++) { int dist = (k - ls[x]) % Z; if(dist < 0) dist += Z; if(rem[k] & 1) cur ^= dist; } ans[x] ^= cur; } } for(int i = 0; i < q; i++) if(ans[i] == 0) printf("B"); else printf("A"); }
1512
A
Spy Detected!
You are given an array $a$ consisting of $n$ ($n \ge 3$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $[4, 11, 4, 4]$ all numbers except one are equal to $4$). Print the index of the element that does not equal others. The numbers in the array are numbered from one.
To find a number that differs from the rest of the numbers in the array, you need to iterate through the array, maintaining two pairs of numbers $(x_1, c_1)$ and $(x_2, c_2)$, where $x_i$ is a number from the array, $c_i$ is how many times the number $x_i$ occurs in the array. Then, to get an answer, you need to find the position of the $x_i$ that occurs in the array exactly once (i.e. $c_i = 1$).
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int n; cin >> n; vector<int> v(n); for (int &e : v) { cin >> e; } vector<int> a = v; sort(a.begin(), a.end()); for (int i = 0; i < n; i++) { if (v[i] != a[1]) { cout << i + 1 << "\n"; } } } int main() { int n; cin >> n; while (n--) { solve(); } return 0; }
1512
B
Almost Rectangle
There is a square field of size $n \times n$ in which two cells are marked. These cells can be in the same row or column. You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes. For example, if $n=4$ and a rectangular field looks like this (there are asterisks in the marked cells): $$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$ Then you can mark two more cells as follows $$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$ If there are several possible solutions, then print any of them.
f two asterisks are in the same row, then it is enough to select any other row and place two asterisks in the same columns in it. If two asterisks are in the same column, then you can do the same. If none of the above conditions are met and the asterisks are at positions $(x1, y1)$, $(x2, y2)$, then you can place two more asterisks at positions $(x1, y2)$, $(x2, y1)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<string> f(n); vector<pair<int,int>> p; forn(i, n) { cin >> f[i]; forn(j, n) if (f[i][j] == '*') p.push_back({i, j}); } p.push_back(p[0]); p.push_back(p[1]); if (p[0].first == p[1].first) { p[2].first = (p[2].first + 1) % n; p[3].first = (p[3].first + 1) % n; } else if (p[0].second == p[1].second) { p[2].second = (p[2].second + 1) % n; p[3].second = (p[3].second + 1) % n; } else swap(p[2].first, p[3].first); f[p[2].first][p[2].second] = '*'; f[p[3].first][p[3].second] = '*'; forn(i, n) cout << f[i] << endl; } }
1512
C
A-B Palindrome
You are given a string $s$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has \textbf{exactly} $a$ characters '0' and \textbf{exactly} $b$ characters '1'. Note that each of the characters '?' is replaced \textbf{independently} from the others. A string $t$ of length $n$ is called a palindrome if the equality $t[i] = t[n-i+1]$ is true for all $i$ ($1 \le i \le n$). For example, if $s=$"01?????0", $a=4$ and $b=4$, then you can replace the characters '?' in the following ways: - "01011010"; - "01100110". For the given string $s$ and the numbers $a$ and $b$, replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has \textbf{exactly} $a$ characters '0' and \textbf{exactly} $b$ characters '1'.
First, let's find such positions $i$ ($1 \le i \le n$) such that $s[i]\ne$'?' (symbols in symmetric positions are uniquely determined): If $s[n-i+1]=$'?', then $s[n-i+1] = s[i]$; If $s[i] \ne s[n-i+1]$, then at the end we will not get a palindrome in any way, so the answer is '-1'. Note that after such a replacement, the remaining characters '?' are split into pairs, except maybe the central one. If the center character is '?' then it is necessary to put the character '0' if $a$ is odd, or '1' if $b$ is odd (if neither $a$, nor $b$ is odd, then the answer is '-1'). Now the remaining characters '?' are split into pairs (i.e. if $s[i]=$'?', then $s[n-i+1]=$'?'). This allows the remaining characters '0' and '1' to be replaced greedily: If $s[i]=$'?' and $a>1$, then $s[i]=s[n-i+1]=$'0' and decrease $a$ for $2$; If $s[i]=$'?' and $b>1$, then $s[i]=s[n-i +1]=$'1' and decrease $b$ for $2$; Otherwise the answer is '-1'.
[ "constructive algorithms", "implementation", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; void no() { cout << "-1" << endl; } void solve() { int a, b; cin >> a >> b; string s; cin >> s; for (int times = 0; times < 2; times++) { for (int i = 0; i < (int) s.size(); i++) { int j = (int) s.size() - i - 1; if (s[i] != '?') { if (s[j] == '?') { s[j] = s[i]; } else if (s[i] != s[j]) { no(); return; } } } reverse(s.begin(), s.end()); } a -= count(s.begin(), s.end(), '0'); b -= count(s.begin(), s.end(), '1'); int ques = count(s.begin(), s.end(), '?'); bool emptyMid = (s.size() % 2 == 1 && s[s.size() / 2] == '?'); if (a < 0 || b < 0 || a + b != ques || (emptyMid && a % 2 == 0 && b % 2 == 0)) { no(); return; } if (a % 2 == 1 || b % 2 == 1) { int i = s.size() / 2; if (s[i] != '?') { no(); return; } s[i] = (a % 2 == 1 ? '0' : '1'); if (a % 2 == 1) { a--; } else { b--; } } if (a % 2 == 1 || b % 2 == 1) { no(); return; } for (int i = 0; i < (int) s.size(); i++) { if (s[i] == '?') { int j = s.size() - i - 1; if (a > 0) { a -= 2; s[i] = s[j] = '0'; } else { b -= 2; s[i] = s[j] = '1'; } } } cout << s << endl; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1512
D
Corrupted Array
You are given a number $n$ and an array $b_1, b_2, \ldots, b_{n+2}$, obtained according to the following algorithm: - some array $a_1, a_2, \ldots, a_n$ was guessed; - array $a$ was written to array $b$, i.e. $b_i = a_i$ ($1 \le i \le n$); - The $(n+1)$-th element of the array $b$ is the sum of the numbers in the array $a$, i.e. $b_{n+1} = a_1+a_2+\ldots+a_n$; - The $(n+2)$-th element of the array $b$ was written some number $x$ ($1 \le x \le 10^9$), i.e. $b_{n+2} = x$; The - array $b$ was shuffled. For example, the array $b=[2, 3, 7, 12 ,2]$ it could be obtained in the following ways: - $a=[2, 2, 3]$ and $x=12$; - $a=[3, 2, 7]$ and $x=2$. For the given array $b$, find any array $a$ that could have been guessed initially.
What is the sum of all the elements in $b$? This is twice the sum of all the elements in $a$ + $x$. Denote by $B$ the sum of all the elements of $b$. Let's iterate over which of the array elements was added as the sum of the elements $a$ (let's denote, for $a$). Then, $x$ = $B-2 \cdot A$. It remains to check that the element $x$ is present in the array $b$, this can be done using a hash table or a binary search tree.
[ "constructive algorithms", "data structures", "greedy" ]
1,200
#include <bits/stdc++.h> using namespace std; void no() { cout << "-1" << endl; } void solve() { int n; cin >> n; vector<int> b(n + 2); for (int &x : b) { cin >> x; } multiset<int> have(b.begin(), b.end()); long long sum = accumulate(b.begin(), b.end(), 0LL); for (int x : b) { have.erase(have.find(x)); sum -= x; if (sum % 2 == 0 && sum <= 2'000'000'000 && have.find(sum / 2) != have.end()) { have.erase(have.find(sum / 2)); for (int y : have) { cout << y << " "; } cout << endl; return; } sum += x; have.insert(x); } no(); } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }