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
1604
A
Era
Shohag has an integer sequence $a_1, a_2, \ldots, a_n$. He can perform the following operation any number of times (possibly, zero): - Select any positive integer $k$ (it can be different in different operations). - Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $k$ into the sequence at this position. - This way, the sequence $a$ changes, and the next operation is performed on this changed sequence. For example, if $a=[3,3,4]$ and he selects $k = 2$, then after the operation he can obtain one of the sequences $[\underline{2},3,3,4]$, $[3,\underline{2},3,4]$, $[3,3,\underline{2},4]$, or $[3,3,4,\underline{2}]$. Shohag wants this sequence to satisfy the following condition: for each $1 \le i \le |a|$, $a_i \le i$. Here, $|a|$ denotes the size of $a$. Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.
If $a_i \gt i$ for some position $i$, then we need to insert at least $a_i - i$ new small elements before this position. Let $m = max(0, \max\limits_{i = 1}^{n}{(a_i - i)})$. So we need at least $m$ operations. But its not hard to see that $m$ operations are enough. For example, you can insert $m$ $1$s at the beginning of the sequence. This way, all elements will be shifted by $m$ positions, and consequently, will satisfy that $a_i \le i$ for each valid $i$.
[ "greedy" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; for (int i = 1; i <= n; i++) { int k; cin >> k; ans = max(ans, k - i); } cout << ans << '\n'; } return 0; }
1604
B
XOR Specia-LIS-t
YouKn0wWho has an integer sequence $a_1, a_2, \ldots a_n$. Now he will split the sequence $a$ into one or more consecutive subarrays so that each element of $a$ belongs to exactly one subarray. Let $k$ be the number of resulting subarrays, and $h_1, h_2, \ldots, h_k$ be the lengths of the longest increasing subsequences of corresponding subarrays. For example, if we split $[2, 5, 3, 1, 4, 3, 2, 2, 5, 1]$ into $[2, 5, 3, 1, 4]$, $[3, 2, 2, 5]$, $[1]$, then $h = [3, 2, 1]$. YouKn0wWho wonders if it is possible to split the sequence $a$ in such a way that the bitwise XOR of $h_1, h_2, \ldots, h_k$ is equal to $0$. You have to tell whether it is possible. The longest increasing subsequence (LIS) of a sequence $b_1, b_2, \ldots, b_m$ is the longest sequence of valid indices $i_1, i_2, \ldots, i_k$ such that $i_1 \lt i_2 \lt \ldots \lt i_k$ and $b_{i_1} \lt b_{i_2} \lt \ldots \lt b_{i_k}$. For example, the LIS of $[2, 5, 3, 3, 5]$ is $[2, 3, 5]$, which has length $3$. An array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
What happens if we split the sequence into subarrays of length $1$?. Yes, if $n$ is even, the bitwise XOR will be $0$ as there will be an even number of $1$s. If $n$ is odd we can't do the same. But what if there is an index $i$ such that $a_i \ge a_{i + 1}$? What if we use these two indices as a single subarray as it has LIS of length $1$ and take other indices as single subarrays? Yeah, again, there will be an even number of $1$s which will yield a bitwise XOR of $0$. What we are left with are strictly increasing sequences of odd lengths. Notice that any subarray of length $l$ has LIS of length $l$ here. So we need to find a sequence $b_1, b_2, \ldots, b_k$ such that $b_1 + b_2 + \ldots + b_k = n$ and $b_1 \oplus b_2 \oplus \ldots \oplus b_k = 0$ where $n$ is odd. Is it possible to find such a sequence? Pause and think. Hint: think about the last bit of each $b_i$. If XOR is $0$, then there will be an even number of $b_i$s such that its last bit is $1$. But then the sum will be even. But here the sum $n$ is odd, which produces a contradiction. So in the last case, it is not possible to find such a split.
[]
1,100
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n + 1); bool inc = true; for (int i = 1; i <= n; i++) { cin >> a[i]; inc &= a[i] > a[i - 1]; } if (n % 2 == 0 or !inc) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
1605
A
A.M. Deviation
A number $a_2$ is said to be the arithmetic mean of two numbers $a_1$ and $a_3$, if the following condition holds: $a_1 + a_3 = 2\cdot a_2$. We define an arithmetic mean deviation of three numbers $a_1$, $a_2$ and $a_3$ as follows: $d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$. Arithmetic means a lot to Jeevan. He has three numbers $a_1$, $a_2$ and $a_3$ and he wants to minimize the arithmetic mean deviation $d(a_1, a_2, a_3)$. To do so, he can perform the following operation any number of times (possibly zero): - Choose $i, j$ from $\{1, 2, 3\}$ such that $i \ne j$ and increment $a_i$ by $1$ and decrement $a_j$ by $1$ Help Jeevan find out the minimum value of $d(a_1, a_2, a_3)$ that can be obtained after applying the operation any number of times.
$\rightarrow$ Applying the operation on $a_1$ and $a_3$ (irrespective of which element is incremented and which one is decremented) does not change the value of $a_1 + a_3 - 2 \cdot a_2$. $\rightarrow$ Incrementing $a_1$ (or $a_3$) by $1$ and decrementing $a_2$ by $1$ causes the value of $a_1 + a_3 - 2 \cdot a_2$ to increase by $3$. $\rightarrow$ Decrementing $a_1$ (or $a_3$) by $1$ and incrementing $a_2$ by $1$ causes the value of $a_1 + a_3 - 2 \cdot a_2$ to decrease by $3$. This effectively means that we can add or subtract any multiple of $3$ by performing some number of operations. Also, the value of $a_1 + a_3 - 2 \cdot a_2$ will never change modulo $3$. Thus, If $\, \, a_1 + a_3 - 2 \cdot a_2 \equiv 0$ $\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |0| = 0$ If $\, \, a_1 + a_3 - 2 \cdot a_2 \equiv 1$ $\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |1| = 1$ If $\, \, a_1 + a_3 - 2 \cdot a_2 \equiv 2$ $\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |2-3| = |-1| = 1$ In simpler words, if $a_1 + a_3 - 2 \cdot a_2$ is divisible by $3$ the answer is $0$, otherwise it is $1$. Time Complexity: $\mathcal{O}(1)$
[ "math", "number theory" ]
800
t=int(input()) for i in range(t): a,b,c=[int(x) for x in input().split()] print(0 if ((a+b+c)%3 == 0) else 1)
1605
B
Reverse Sort
Ashish has a binary string $s$ of length $n$ that he wants to sort in non-decreasing order. He can perform the following operation: - Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $k$ such that $1 \leq k \leq n$ and any sequence of $k$ indices $1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$ such that $s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$. - Reverse this subsequence in-place. Formally, swap $s_{i_1}$ with $s_{i_k}$, swap $s_{i_2}$ with $s_{i_{k-1}}$, $\ldots$ and swap $s_{i_{\lfloor k/2 \rfloor}}$ with $s_{i_{\lceil k/2 \rceil + 1}}$ (Here $\lfloor x \rfloor$ denotes the largest integer not exceeding $x$, and $\lceil x \rceil$ denotes the smallest integer not less than $x$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $n$ operations.
Any binary string $s$ can be sorted in at most $1$ operation! Let the number of $0$s in $s$ be $cnt_0$ and the number of $1$s in $s$ be $cnt_1$. The first $cnt_0$ positions of the final sorted string will be $0$ and the remaining $cnt_1$ positions will be $1$ (since it is sorted in non-decreasing order). Key observation: For every $1$ that is in the first $cnt_0$ positions of $s$, there is a $0$ that is in the last $cnt_1$ positions of $s$ (Why?). If the string is not already sorted, in one operation pick the subsequence consisting of all $1$s among the first $cnt_0$ positions of $s$ as well as all $0$s among the last $cnt_1$ positions of $s$. It can be shown that this will correctly sort the string since the number of such $0$s and $1$s are equal. Time complexity: $\mathcal{O}(n)$
[ "greedy", "sortings" ]
1,000
q = int(input()) for tc in range(q): n = int(input()) s = input() t = ''.join(sorted(s)) ans = [] for i in range(len(s)): if s[i] != t[i]: ans.append(i) val = 1 if len(ans) > 0 else 0 print(val) if val > 0: print(len(ans), end = " ") for elem in range(len(ans)): print(ans[elem] + 1, end = " ") print()
1605
C
Dominant Character
Ashish has a string $s$ of length $n$ containing only characters 'a', 'b' and 'c'. He wants to find the length of the smallest substring, which satisfies the following conditions: - Length of the substring is \textbf{at least} $2$ - 'a' occurs strictly more times in this substring than 'b' - 'a' occurs strictly more times in this substring than 'c' Ashish is busy planning his next Codeforces round. Help him solve the problem. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Tl;dr: The following are all the possible minimal substrings (there aren't that many) which satisfy the given conditions: "aa", "aba", "aca", "abca", "acba", "abbacca", "accabba". Any other string that satisfies the condition contains at least one of these as a substring, and hence is not the optimal substring for the answer. Claim: If a substring exists which satisfies the given conditions, then the length of the shortest such substring is at most $7$. Otherwise the solution does not exist. Proof: Let us consider that the solution exists. We will try to prove this by breaking this into the following cases: Case 1: There exist two such "a" whose distance is less than or equal to $2$, where distance is the absolute difference of their indices. In this case where there are two such "a" whose distance is less than $2$, then either these two "a" are present consecutive or there is only one single letter between these two "a". All these minimal substrings are "aa", "aba" and "aca"which satisfies all the given conditions. Hence we can say that the shortest length of such substring that satisfies the given conditions is at most $3$ in this case. Case 2: There exists no two such "a" whose distance is less than or equal to $2$. In this case all the consecutive occurrences of "a" are present at a distance at least $3$. Then in order for the number of "a" to be bigger than that of "b" and "c" the string must look like "a??a??a??a??a". Let us define "??" as a block. Now if there is any block consisting of different characters $i.e$ "bc" or "cb" then the substring "a??a" will satisfy all the given conditions and hence the minimal length will be $4$. Notice that there must be at least one block of "bb" and atleast one block of "cc", otherwise "a" will not be in a majority. Hence, there must exist 2 consecutive blocks equal to "bb" and "cc" or "cc" and "bb" in the string (otherwise all blocks would be of the same character). Hence we can pick the substring "abbacca" or "accabba" which satisfies the given conditions. The minimal length is, therefore, $7$ in this case. Therefore we can say that the shortest length of such substring that satisfies the given conditions is at most $7$ in this case. Thus, it suffices to only check all substrings of length up to $7$ and find the smallest among them that satisfies the given conditions (or report that it does not exist). Time Complexity: $\mathcal{O}(7 \cdot n)$
[ "brute force", "greedy", "implementation", "strings" ]
1,400
fun main(args: Array<String>) { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val s = readLine()!! var ans = 8; for(i in 0..n-1) { val cnt = IntArray(3) {0} for(j in i..Math.min(i + 6, n - 1)) { cnt[s[j] - 'a']++; if(j > i && cnt[0] > Math.max(cnt[1], cnt[2])) ans = Math.min(ans, j - i + 1); } } if(ans > 7) ans = -1; println(ans) } }
1605
D
Treelabeling
Eikooc and Sushi play a game. The game is played on a tree having $n$ nodes numbered $1$ to $n$. Recall that a tree having $n$ nodes is an undirected, connected graph with $n-1$ edges. They take turns alternately moving a token on the tree. \textbf{Eikooc makes the first move, placing the token} on any node of her choice. Sushi makes the next move, followed by Eikooc, followed by Sushi, and so on. In each turn after the first, a player must move the token to a node $u$ such that - $u$ is adjacent to the node $v$ the token is currently on - $u$ has not been visited before - $u \oplus v \leq min(u, v)$ Here $x \oplus y$ denotes the bitwise XOR operation on integers $x$ and $y$. Both the players play optimally. The player who is unable to make a move loses. The following are examples which demonstrate the rules of the game. \begin{center} \begin{tabular}{ll} Suppose Eikooc starts the game by placing the token at node $4$. Sushi then moves the token to node $6$, which is unvisited and adjacent to $4$. It also holds that $6 \oplus 4 = 2 \leq min(6, 4)$. In the next turn, Eikooc moves the token to node $5$, which is unvisited and adjacent to $6$. It holds that $5 \oplus 6 = 3 \leq min(5, 6)$. Sushi has no more moves to play, so she loses. & Suppose Eikooc starts the game by placing the token at node $3$. Sushi moves the token to node $2$, which is unvisited and adjacent to $3$. It also holds that $3 \oplus 2 = 1 \leq min(3, 2)$. Eikooc cannot move the token to node $6$ since $6 \oplus 2 = 4 \nleq min(6, 2)$. Since Eikooc has no moves to play, she loses. \ \end{tabular} \end{center} Before the game begins, Eikooc decides to sneakily relabel the nodes of the tree in her favour. Formally, a relabeling is a permutation $p$ of length $n$ (sequence of $n$ integers wherein each integer from $1$ to $n$ occurs exactly once) where $p_i$ denotes the new numbering of node $i$. She wants to maximize the number of nodes she can choose in the first turn which will guarantee her a win. Help Eikooc find any relabeling which will help her do so.
If the most significant bits (MSBs) of two integers $x$ and $y$ are the same, say $\mathrm{MSB}_x = \mathrm{MSB}_y = b$, then the $b$-th bit will be unset in $x \oplus y$. Since $min(x, y)$ will have this bit set, it will be greater than $x \oplus y$. Thus, if $\mathrm{MSB}_x = \mathrm{MSB}_y$ then $x \oplus y \leq min(x, y)$. If a node in the tree is adjacent only to nodes whose MSB differs from its MSB, then the player who plays this node will win. It turns out that not only is it always possible to make it such that no two nodes sharing an edge have the same MSB, it is also necessary to do so in order to maximize the number of winnning starting nodes for Eikooc. Consequently, starting at any node will guarantee a win for her. Why is it necessary if it is always possible? $\\$ Assume there exists at least two nodes in the tree that are adjacent to each other, having the same MSB. We prove that there will be at least one losing node for Eikooc to start on, which is suboptimal. $\\$ Consider a connected component of nodes in the tree of size at least two, all having the same MSB. Since this connected component also forms a tree, it must have at least one leaf node. Any node in the component which is adjacent to at least one of these leaf nodes will be losing for Eikooc (since Sushi can just move the token to a leaf node and Eikooc will have no moves to play). How do you construct it and is it always possible to do so (if so, why)? $\\$ We aim to relabel the nodes of the tree in such a way that for every node $v$ in the tree and all nodes $u$ adjacent to it, $\mathrm{MSB}_v \neq \mathrm{MSB}_u$. $\\$ Think bipartite. In the bipartite colouring of a tree, no two adjacent nodes have the same colour. If we are able to relabel the nodes in such a way that all nodes with the same MSB belong to the same colour, we are done. $\\$ Key observation: There are $2^i$ occurrences of integers from $1$ to $n$ with the $i$-th bit as MSB (0-indexed) for each $i$ from $0$ to $\mathrm{MSB}_n - 1$, and all such groups of integers are disjoint (since each integer has exactly one MSB). $\\$ Let the number of white and black nodes be $w$ and $b$ respectively and WLOG let $w \leq b$ (we can swap the colours otherwise). Since all nodes are coloured either white or black, $w + b = n$. Under these constraints, it is then easy to show that $w \leq \frac{n}{2}$. Consequently, $\mathrm{MSB}_w \lt \mathrm{MSB}_n$. Since $\mathrm{MSB}_w \lt \mathrm{MSB}_n$, $w$ can possibly only have those bits set which lie in the range $[0, \mathrm{MSB}_n - 1]$. Can you connect the dots? $\\$ Consider the binary representation of $w$. We can assign all integers from $1$ to $n$ having the $i$-th bit as MSB to a white node if the $i$-th bit is set in $w$, and assign all the remaining integers to black nodes. In doing so, no two nodes having the same MSB will belong to different colours. This ensures that no such pair is adjacent. This is also guaranteed to always be possible since the binary representation of $w$ only spans the first $\mathrm{MSB}_n - 1$ bits and we also have access to groups of sizes comprising all powers of two upto $\mathrm{MSB}_n - 1$. Time complexity: $\mathcal{O}(n)$
[ "bitmasks", "constructive algorithms", "dfs and similar", "games", "greedy", "implementation", "trees" ]
2,100
fun dfs(x: Int, p: Int, curcol: Int, adj: Array<MutableList<Int>>, col: Array<Int>) { col[x] = curcol adj[x] .filter { it != p } .forEach { dfs(it, x, curcol xor 1, adj, col) } } fun main(args: Array<String>) { val t = readLine()!!.toInt() repeat(t) { val n = readLine()!!.toInt() val adj = Array(n) { mutableListOf<Int>() } repeat(n - 1) { val (u, v) = readLine()!!.split(" ").map { it.toInt() } adj[u - 1].add(v - 1); adj[v - 1].add(u - 1); } val col = Array<Int>(n) {0} dfs(0, -1, 0, adj, col) var s = Array(2) { mutableListOf<Int>() } (0..n-1).forEach { s[col[it]].add(it) } if(s[0].size < s[1].size) s[0] = s[1].also { s[1] = s[0] } val highestBit = Array(20) { mutableListOf<Int>() } (1..n).forEach { highestBit[it.takeHighestOneBit().countTrailingZeroBits()].add(it - 1) } val ans = Array<Int>(n) {-1} (19 downTo 0).forEach { currentBit -> val largerSet = if(s[0].size >= s[1].size) 0 else 1 highestBit[currentBit].forEach { it -> ans[it] = s[largerSet].last() s[largerSet].removeLast() } } val pos = Array<Int>(n) {-1} (0..n-1).forEach { pos[ans[it]] = it }; (0..n-1).forEach { print ("${pos[it] + 1} ") } println() } }
1605
E
Array Equalizer
Jeevan has two arrays $a$ and $b$ of size $n$. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations: - Choose any $i$ ($1 \le i \le n$) and increment $a_j$ by $1$ for every $j$ which is a multiple of $i$ and $1 \le j \le n$. - Choose any $i$ ($1 \le i \le n$) and decrement $a_j$ by $1$ for every $j$ which is a multiple of $i$ and $1 \le j \le n$. He wants to convert array $a$ into an array $b$ using the minimum total number of operations. However, Jeevan seems to have forgotten the value of $b_1$. So he makes some guesses. He will ask you $q$ questions corresponding to his $q$ guesses, the $i$-th of which is of the form: - If $b_1 = x_i$, what is the minimum number of operations required to convert $a$ to $b$? Help him by answering each question.
Firstly let's observe that only the differences $b_i - a_i$ matter, and not the individual values of $a_i$ and $b_i$. So let us create two more arrays $A$ and $B$ where initially $A_i = 0$ and $B_i = b_i - a_i$ for all $i$. The problem reduces to making $A$ equal to $B$. Let's have a few definitions for ease of explanation. We define operation "add" $k$ to $i$ as: perform the increment operation at $i$ (and multiples of $i$), $k$ times, if $k > 0$, otherwise perform the decrement operation at $i$ (and multiples of $i$), $k$ times. In both cases, the number of operations performed is $|k|$. Let's first solve the problem for only one value of $B_1$. We notice that problem can be solved using a simple greedy approach. We iterate over the elements from left to right. Let the index of the current element be $u$. Initial arrays: -123456$\cdots$$A$$0$$0$$0$$0$$0$$0$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add------$\cdots$ -123456$\cdots$$A$$0$$0$$0$$0$$0$$0$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add------$\cdots$ At $u = 1$: Applying the operation at $i = 1$ alone can change the value of $A_1$. Thereby we "add" $B_1$ at $i = 1$ to make $A_1 = B_1$. The remaining array also gets modified accordingly. Resulting arrays: -123456$\cdots$$A$$B_1$$B_1$$B_1$$B_1$$B_1$$B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$-----$\cdots$ -123456$\cdots$$A$$B_1$$B_1$$B_1$$B_1$$B_1$$B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$-----$\cdots$ At $u = 2$: Applying the operation at $i = 1$ and $i = 2$ only can change the value of $A_2$. But since we have already made $A_1 = B_1$, we will only apply operations at $i = 2$. We "add" $B_2 - B_1$ at $i = 2$. Resulting arrays: -123456$\cdots$$A$$B_1$$B_2$$B_1$$B_2$$B_1$$B_2$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$----$\cdots$ -123456$\cdots$$A$$B_1$$B_2$$B_1$$B_2$$B_1$$B_2$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$----$\cdots$ At $u = 3$: Applying the operation at $i = 1$ and $i = 3$ only can change the value of $A_3$. But since we have already made $A_1 = B_1$, we will only apply operations at $i = 3$. We "add" $B_3 - B_1$ at $i = 3$. Resulting arrays: -123456$\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$---$\cdots$ -123456$\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$---$\cdots$ At $u = 4$: Applying the operation at $i = 1$, $i = 2$ and $i = 4$ only can change the value of $A_4$. But since we have already made $A_1 = B_1$ and $A_2$ = B_2, we will only apply operations at $i = 4$. We "add" $B_4 - B_2$ at $i = 4$. Resulting arrays: -123456$\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$$B_4 - B_2$--$\cdots$ -123456$\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$$B_4 - B_2$--$\cdots$ So we iterate from left to right and at every index $u$, we "add" $(B_u -$ current value of $A_u)$ at $i = u$. The final answer will be summation of absolute value of these values (i.e. the values written in the "add" row). However, in the original problem, we have to solve the problem for multiple values of $B_1$. So let us assume the value of $B_1$ to be equal to some variable, say $x$. Let us try to use the same approach with the variable $x$. Initial arrays: -123456$\cdots$$A$$0$$0$$0$$0$$0$$0$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add------$\cdots$ -123456$\cdots$$A$$0$$0$$0$$0$$0$$0$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add------$\cdots$ At $u = 1$: We "add" $x$ at $i = 1$. Resulting arrays: -123456$\cdots$$A$$x$$x$$x$$x$$x$$x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$-----$\cdots$ -123456$\cdots$$A$$x$$x$$x$$x$$x$$x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$-----$\cdots$ At $u = 2$: We "add" $B_2 - x$ at $i = 2$. Resulting arrays: -123456$\cdots$$A$$x$$B_2$$x$$B_2$$x$$B_2$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$----$\cdots$ -123456$\cdots$$A$$x$$B_2$$x$$B_2$$x$$B_2$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$----$\cdots$ At $u = 3$: We "add" $B_3 - x$ at $i = 3$. Resulting arrays: -123456$\cdots$$A$$x$$B_2$$B_3$$B_2$$x$$B_3 + B_2 - x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$$B_3 - x$---$\cdots$ -123456$\cdots$$A$$x$$B_2$$B_3$$B_2$$x$$B_3 + B_2 - x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$$B_3 - x$---$\cdots$ At $u = 4$: We "add" $B_4 - B_2$ at $i = 4$. Resulting arrays: -123456$\cdots$$A$$x$$B_2$$B_3$$B_4$$x$$B_3 + B_2 - x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$$B_3 - x$$B_4 - B_2$--$\cdots$ -123456$\cdots$$A$$x$$B_2$$B_3$$B_4$$x$$B_3 + B_2 - x$$\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\cdots$add$x$$B_2 - x$$B_3 - x$$B_4 - B_2$--$\cdots$ Every cell in the "add" row here will be of the form: $c \cdot x + d$. The final answer will be the summation of absolute values of these values written in the "add" row. Also we know, $|c \cdot x + d| = \begin{cases} c \cdot x + d & x \ge -\frac{d}{c} \\ -(c \cdot x + d) & x \lt -\frac{d}{c} \end{cases}$ Note that the above equalities hold only when $c \gt 0$. So if $c$ is negative in any term, then we can multiply the entire term with $-1$ to make it positive since $|c \cdot x + d| = |- c \cdot x - d|$. Now, we can store the values of $-\frac{d}{c}$ for each index in sorted order. And for each query, we can find out, using binary search, which of the absolute value terms will have a positive sign and which of those will have a negative sign. So we can finally calculate the answer using prefix and suffix sums. Bonus: It turns out that the value of coefficient of $x$ in the "add" value for the $u$-th index is $c_u = \mu(u)$ where $\mu$ is the mobious function. So $-1 \le c_u \le 1$. Time Complexity: $\mathcal{O}(n \log n + q \log n)$ $\cdots$
[ "binary search", "greedy", "implementation", "math", "number theory", "sortings", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define int long long #define endl "\n" #define sz(w) (int)(w.size()) using pii = pair<int, int>; const double EPS = 1e-9; const long long INF = 1e18; const int N = 2e5+5; int n, m, a[N], b[N], c[N], add[N], mob[N]; void mobius() { mob[1] = 1; for(int i = 2; i < N; i++) { mob[i]--; for(int j = i + i; j < N; j += i) { mob[j] -= mob[i]; } } } int32_t main() { IOS; mobius(); cin >> n; for(int i = 1; i <= n; i++) cin >> a[i]; for(int i = 1; i <= n; i++) cin >> b[i]; for(int i = 1; i <= n; i++) c[i] = b[i] - a[i]; c[1] = 0; vector<int> z; for(int i = 1; i <= n; i++) { int d = c[i]; for(int j = i; j <= n; j += i) { c[j] -= d; } add[i] = d; } int ans = 0; for(int i = 1; i <= n; i++) { if(mob[i] == 0) ans += abs(add[i]); else if(mob[i] == -1) z.push_back(-add[i]); else z.push_back(add[i]); } sort(z.begin(), z.end()); vector<int> pref = z; for(int i = 1; i < sz(z); i++) pref[i] = pref[i-1] + z[i]; auto sum = [&pref](int l, int r) { if(r < 0) return 0LL; int res = pref[r]; if(l-1 >= 0) res -= pref[l-1]; return res; }; int q; cin >> q; while(q--) { int x; cin >> x; x -= a[1]; int lo = 0, hi = sz(z)-1; while(lo <= hi) { int mid = (lo+hi)/2; if(z[mid] <= -x) lo = mid+1; else hi = mid-1; } swap(lo, hi); int res = sum(hi, sz(z)-1) + (sz(z)-hi) * x; res -= (sum(0, lo) + (lo+1)*x); cout << ans+res << endl; } return 0; }
1605
F
PalindORme
An integer array $a$ of length $n$ is said to be a PalindORme if ($a_{1}$ $|$ $a_{2} $ $|$ $ \ldots $ $|$ $ a_{i}) = (a_{{n - i + 1}} $ $|$ $ \ldots $ $|$ $ a_{{n - 1}} $ $|$ $ a_{n}) $ \textbf{for all} $ 1 \leq i \leq n$, where $|$ denotes the bitwise OR operation. An integer array $a$ of length $n$ is considered to be good if its elements can be rearranged to form a PalindORme. Formally, array $a$ is good if there exists a permutation $p_1, p_2, \ldots p_n$ (an array where each integer from $1$ to $n$ appears exactly once) for which $a_{p_1}, a_{p_2}, \ldots a_{p_n}$ is a PalindORme. Find the number of good arrays of length $n$, consisting only of integers in the range $[0, 2^{k} - 1]$, and print it modulo some prime $m$. Two arrays $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$ are considered to be different if there exists any $i$ $(1 \leq i \leq n)$ such that $a_i \ne b_i$.
$\textbf{Solution Outline:}$ For any bad array, there is $\textbf{exactly one}$ maximum even length good subsequence (possibly the empty subsequence). It can be proven that there exists at most one element in the bad array that doesn't belong to this subsequence, but is a submask of its OR. If such an element exists, we add it to the subsequence. After performing this step if needed, we have a good subsequence of this bad array such that all other elements of this array have one or more bits active which aren't present anywhere in this subsequence. We will call this the "best" subsequence from now on. Clearly a bad array also has $\textbf{exactly one}$ best subsequence. By noting that the best subsequence is still a good array (place the extra element in the middle of the PalindORme of even length), we can use dp to count the number of bad arrays of length $n$ with exactly $k$ bits on in total using its best subsequence of length $n' \lt n$ with exactly $k' \lt k$ bits on in total in $O(n ^ 4)$. $\textbf{Full Editorial:}$ Let $S$ be the multiset of elements of the initial array $a_1, a_2, \ldots, a_n$. We want to check if we can construct a PalindORme from these elements. Out of the $n$ conditions of the form $b_{1}$ $|$ $b_{2}$ $|$ $\ldots$ $|$ $b_{i} = b_{{n - i + 1}}$ $|$ $\ldots$ $|$ $b_{{n - 1}}$ $|$ $b_{n}$, it intuitively makes sense to tackle them in increasing order of $i$, so we will try to do that. For $i = 1$, we want to find two elements $x, y$ in $S$ such that $x = y$. We place these elements as $b_1$ and $b_n$ and erase them from $S$. For $i = 2$, we want to find two elements $x, y$ in $S$ such that $b_1$ $|$ $x$ $=$ $b_1$ $|$ $y$. We place these elements as $b_2$ and $b_{n - 1}$ and erase them from $S$. Generalizing, for any $i$, we want to find two elements $x, y$ in $S$ such that $b_{1}$ $|$ $b_{2}$ $|$ $\ldots$ $|$ $b_{i - 1}$ $|$ $x$ $=$ $b_{1}$ $|$ $b_{2}$ $|$ $\ldots$ $|$ $b_{i - 1}$ $|$ $y$. We place these elements as $b_i$ and $b_{n + 1 - i}$ and erase them from $S$. But what if there exists multiple pairs $(x_1, y_1), (x_2, y_2), \ldots (x_k, y_k)$ that satisfy the property in a given step, which do we take? It is optimal to take any of them. Clearly if $mask$ $|$ $x_j$ = $mask$ $|$ $y_j$, then $mask$ $|$ $z$ $|$ $x_j$ = $mask$ $|$ $z$ $|$ $y_j$ is also true for any $z$. So regardless of which of these pairs we take, all other pairs will remain good in future steps. So we obtain the following simple algorithm to check if a PalindORme is good: This algorithm is equivalent to placing elements at positions $i$ and $(n + 1 - i)$ of the PalindORme in the $i$-th iteration of the loop. Taking any two elements is optimal since a pair that satisfies the property for $mask$ will also clearly satisfy it for $mask$ $|$ $x$. Let us consider the multiset $S$ corresponding to the elements of a bad array: This algorithm will fail to find any such pair of elements after some number of steps. The pairs which have been selected till this point will constitute a good array (possibly of length 0). For the given bad array, the number of pairs taken as well as the bits on in the mask will always be the same when the algorithm fails regardless of the two elements selected in each step. Since we cannot add any two more elements to this good array, this is the longest even length good subsequence of the bad array. Due to the previous point, we can also see that it is the only good subsequence of this length. There can exist at most one element among the remaining elements not in the subsequence which is a submask of $mask$, otherwise there would exist a pair such that $mask$ $|$ $x$ $=$ $mask$ $|$ $y$ $=$ $mask$. If such an element exists, we can add it to the subsequence. The best subsequence still remains a good array since we can place this element in the center position of resulting PalindORme. After performing this step if needed, we have a good subsequence of this bad array such that all elements of this array not in the subsequence have one or more bits active which aren't on in $mask$ and therefore not present in the subsequence. We will call this the "best" subsequence from now on. Clearly a bad array also has $\textbf{exactly one}$ best subsequence (possibly of length 0). So every bad array of length $n$ with $k$ bits on in total can be mapped to a best subsequence (which is a good array) with length $n' \lt n$ with $k' \lt k$ bits on in total. The remaining $n - n'$ elements will then need to be chosen such that they have the remaining $k - k'$ bits on in total while possessing distinct values when OR'd with $mask$. So we obtain a dp to count the number of bad arrays $-$ $cnt\_bad_{\text{length}, \text{bits on in total}}$, where $cnt\_bad_{i, j} = \sum\limits_{i' = 0}^{i - 1} \sum\limits_{j' = 0}^{j - 1} f(i, j, i', j')\cdot(cnt\_good_{i', j'})$. Here $f(i, j, i', j')$ is the number of bad arrays of length $i$ with exactly $j$ bits on in total, that have a good array of length $i' \lt i$ with exactly $j' \lt j$ bits on in total as their best subsequence. Since the total number of arrays of length $x$ with exactly $y$ bits on in total can be easily calculated using some basic combinatorial formulas and inclusion exclusion, we can rewrite this as: $cnt\_bad_{i, j}$ $=$ $\sum\limits_{i' = 0}^{i - 1} \sum\limits_{j' = 0}^{j - 1} f(i, j, i', j')\cdot(cnt\_total_{i', j'} - cnt\_bad_{i', j'})$ giving us a dp with $O(n ^ 2)$ states and $O(n ^ 4)$ transitions. $f(i, j, i', j')$ is made of the following components: The number of ways of placing the best subsequence in the bad array. Since there are no values in common between the best subsequence and the remaining values of the array, the answer is just $n \choose n'$. Since there are no values in common between the best subsequence and the remaining values of the array, the answer is just $n \choose n'$. The number of ways of choosing which $j'$ of the $j$ bits were from the good array. All ways are possible, so it is just $j \choose j'$ All ways are possible, so it is just $j \choose j'$ The number of different arrays of length $i - i'$ with the remaining $j - j'$ bits set in total such that each element has one or more of the $j - j'$ bits set and all elements have distinct values when OR'd with $mask$, i.e, the remaining $j$ bits. We can observe that the second can be broken into the product of two easier parts: The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\cdot(j')}$. We can observe that the second can be broken into the product of two easier parts: The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\cdot(j')}$. The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\cdot(j')}$. Since these three components are independent of each other, $f(i, j, i', j')$ is just the product of them. However, as you may have observed, the "bad" arrays counted by this dp doesn't line up with the actual definition of bad arrays in one case - When a "bad" array has an even length best subsequence and a single remaining element with one or more bits that aren't set in this subsequence. This is clearly a good array but is counted as bad by our dp. (Example: good array [1, 1] combined with remaining element array [2] resulting in [1, 2, 1] (or [1, 1, 2] / [2, 1, 1]) which is clearly a good array but is counted as bad by our dp.) This is however necessary since this is the only type of good array that is never the best subsequence of any bad array. Counting it as a good array in our dp would lead to overcounting when it was used as a best subsequence. But then how do we then recover the correct number of actual bad arrays of length $n$ with exactly $j$ bits set? We can notice that this case occurs for best subsequences of length $i - 1$ when $i$ is odd. So when counting the number of bad arrays of length $n$ we can just skip best subsequences of length $n - 1$ if $n$ is odd. Since $n$ is the largest array size we are concerned with, good arrays of size $n$ will never be a best subsequence of a larger bad array and as such won't lead to overcounting. As a final note, remember that we have the number of bad arrays for $n$ with $\textbf{exactly}$ $j$ bits set while we need the number of bad arrays with $\textbf {up to}$ $j$ bits set. This can be easily obtained by multiplying the answer for a given $j$ with the number of ways of choosing $j$ of the $k$ bits and summing these values up for each $j$. In short, we want $\sum_{j = 0}^{k} {k \choose j} \cdot cnt\_good_{n, j}$. Time Complexity: $\mathcal{O}(n ^ 4)$ $\cdots$
[ "combinatorics", "dp" ]
2,900
fun mod_expo(base: Int, pow: Int, MOD: Int): Long { if(pow == 0) { return 1; } var res = mod_expo(base, pow / 2, MOD) res = (res * res) % MOD if(pow % 2 == 1) { res = (res * base) % MOD; } return res; } fun mod_inv(base: Int, MOD: Int): Long { return mod_expo(base, MOD - 2, MOD) } fun fast_nCr(n: Int, r: Int, fact: Array<Long>, invfact: Array<Long>, MOD: Int): Long { val num = fact[n]; val denom = (invfact[r] * invfact[n - r]) % MOD; return (num * denom) % MOD; } fun slow_nPr(n: Int, r: Int, MOD: Int): Long { var res = 1L; for(i in 1..r) { res *= (n - i + 1 + MOD) % MOD; res %= MOD; } return res; } fun main(args: Array<String>) { val (n, k, MOD) = readLine()!!.split(" ").map { it.toInt() } val fact = Array<Long>(Math.max(n, k) + 1) { 1L } val invfact = Array<Long>(Math.max(n, k) + 1) { 1L } for(i in 1..Math.max(n, k)) { fact[i] = (fact[i - 1] * i) % MOD invfact[i] = mod_inv(fact[i].toInt(), MOD) } val pow2 = Array<Long>(n * k + 1) { 1 } for(i in 1..n*k) { pow2[i] = (pow2[i - 1] * 2) % MOD; } val cntDistinctPositive = Array(n + 1) { Array<Long>(k + 1) { 0L } } val cntTotal = Array(n + 1) { Array<Long>(k + 1) { 0L } } val cntBad = Array(n + 1) { Array<Long>(k + 1) { 0L } } for(i in 0..n) { for(j in 0..k) { cntDistinctPositive[i][j] = slow_nPr((mod_expo(2, j, MOD).toInt() - 1 + MOD) % MOD, i, MOD) cntTotal[i][j] = pow2[i * j] for(l in 0..j-1) { cntDistinctPositive[i][j] += (MOD - ((fast_nCr(j, l, fact, invfact, MOD) * cntDistinctPositive[i][l])) % MOD) cntDistinctPositive[i][j] = cntDistinctPositive[i][j] % MOD cntTotal[i][j] += (MOD - ((fast_nCr(j, l, fact, invfact, MOD) * cntTotal[i][l])) % MOD); cntTotal[i][j] = cntTotal[i][j] % MOD } } } cntTotal[0][0] = 1 for(i in 1..n) { for(j in 0..k) { cntBad[i][j] = 0 for(a in 0..i-1) { for(b in 0..j-1) { if(i == n && n % 2 == 1 && a == i - 1) { continue; } var curBad = (cntTotal[a][b] - cntBad[a][b] + MOD) % MOD curBad *= (cntDistinctPositive[i - a][j - b]) curBad = curBad % MOD curBad *= fast_nCr(i, a, fact, invfact, MOD) curBad = curBad % MOD curBad *= fast_nCr(j, b, fact, invfact, MOD) curBad = curBad % MOD curBad *= pow2[(i - a) * b] curBad = curBad % MOD cntBad[i][j] += curBad cntBad[i][j] = cntBad[i][j] % MOD } } } } var ans = 0L for(j in 0..k) { val cntGood = (cntTotal[n][j] - cntBad[n][j] + MOD) % MOD ans += (fast_nCr(k, j, fact, invfact, MOD) * cntGood) % MOD } println(ans % MOD) }
1606
A
AB Balance
You are given a string $s$ of length $n$ consisting of characters a and/or b. Let $\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a \textbf{substring}. Analogically, $\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a \textbf{substring}. In one step, you can choose any index $i$ and replace $s_i$ with character a or b. What is the minimum number of steps you need to make to achieve $\operatorname{AB}(s) = \operatorname{BA}(s)$? \textbf{Reminder:} The number of occurrences of string $d$ in $s$ as substring is the number of indices $i$ ($1 \le i \le |s| - |d| + 1$) such that substring $s_i s_{i + 1} \dots s_{i + |d| - 1}$ is equal to $d$. For example, $\operatorname{AB}($aabbbabaa$) = 2$ since there are two indices $i$: $i = 2$ where {a\underline{ab}bbabaa} and $i = 6$ where {aabbb\underline{ab}aa}.
Let's look at the first and the last characters of $s$. Note that if $s_1 = s_n$ (where $n = |s|$), then $\operatorname{AB}(s)$ is always equal to $\operatorname{BA}(s)$. It can be proved, for example, by induction: if $s$ consists of equal characters then $\operatorname{AB}(s) = \operatorname{BA}(s) = 0$; if $s$ has a structure like abb...ba (or baa...ab) then $\operatorname{AB}(s) = \operatorname{BA}(s) = 1$. Otherwise, there is at least one character $s_i$ in the middle that equal to $s_1$ and $s_n$. So we can split string $s$ in $s[1..i]$ and $s[i..n]$. Both these string has $\operatorname{AB} = \operatorname{BA}$ (by induction), so our string $s$ also has $\operatorname{AB}(s) = \operatorname{BA}(s)$. As a result, if $s_1 = s_n$ then the answer is $0$, and we print the string untouched. Otherwise, we replace either $s_1$ or $s_n$ and get the desired string. (It also can be proved that if $s_1 \neq s_n$ then $\operatorname{AB}(s) \neq \operatorname{BA}(s)$)
[ "strings" ]
900
fun main() { repeat(readLine()!!.toInt()) { val s = readLine()!! println(s.last() + s.substring(1)) } }
1606
B
Update Files
Berland State University has received a new update for the operating system. Initially it is installed only on the $1$-st computer. Update files should be copied to all $n$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour. Your task is to find the minimum number of hours required to copy the update files to all $n$ computers if there are only $k$ patch cables in Berland State University.
Let $cur$ be the current number of computers with the update already installed (initially it is $1$). Then, in $1$ hour, we can increase $cur$ by $\min(cur, k)$. From here we can see that the value of $cur$ will double for the first few hours, and then, when it becomes greater than $k$, it will begin to increase by exactly $k$. The process when the number of computers doubles can be modeled using a loop, because the number of doublings does not exceed $\log{n}$. And after that, we have to increase the answer by $\left\lceil {\frac{n - cur}{k}} \right\rceil$ to take the number of additions of $k$ into account. Note that computing $\left\lceil {\frac{n - cur}{k}} \right\rceil$ should be done without using fractional data types; to calculate $\left\lceil {\frac{x}{y}} \right\rceil$ in integers, you should divide $x + y - 1$ by $y$ using integer division (this will work provided that both $x$ and $y$ are non-negative, and $y \ne 0$). If you use real numbers, this may cause precision issues.
[ "greedy", "implementation", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { li n, k; cin >> n >> k; li ans = 0, cur = 1; while (cur < k) { cur *= 2; ++ans; } if (cur < n) ans += (n - cur + k - 1) / k; cout << ans << '\n'; } }
1606
C
Banknotes
In Berland, $n$ different types of banknotes are used. Banknotes of the $i$-th type have denomination $10^{a_i}$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $1$. Let's denote $f(s)$ as the minimum number of banknotes required to represent exactly $s$ burles. For example, if the denominations of banknotes used in Berland are $1$, $10$ and $100$, then $f(59) = 14$: $9$ banknotes with denomination of $1$ burle and $5$ banknotes with denomination of $10$ burles can be used to represent exactly $9 \cdot 1 + 5 \cdot 10 = 59$ burles, and there's no way to do it with fewer banknotes. For a given integer $k$, find the minimum positive number of burles $s$ that cannot be represented with $k$ or fewer banknotes (that is, $f(s) > k$).
First of all, let's find out how to calculate $f(s)$. This can be done greedily, let's iterate from the higher denominations to the lower ones, the number of banknotes of $i$-th type is equal to $\left\lfloor {\frac{s}{10^{a_i}}} \right\rfloor$ (the value of $s$ here changes to reflect that we have already taken some banknotes; that is, we subtract $\left\lfloor {\frac{s}{10^{a_i}}} \right\rfloor \cdot 10^{a_i}$ from $s$ each time, which is the same as taking $s$ modulo $10^{a_i}$). We can see that after we process the $i$-th type of banknotes, the condition $s < 10^{a_i}$ holds, which means that the number of banknotes of $i$-th type does not exceed $\frac{10^{a_{i + 1}}}{10^{a_i}} - 1$ (except in the case of $i = n$). Now we can find the minimum number $s$ such that $f(s) > k$. Let $\mathit{lft}$ be the number of banknotes that still remains to take, initially equal to $k+1$ (because we want $f(s)$ to be at least $k + 1$). Let's iterate from the lower denominations to the highest ones, the number of banknotes of $i$-th type we take should be equal to $\min(\mathit{lft}, \frac{10^{a_{i + 1}}}{10^{a_i}} - 1)$ - the minimum of how many we need to take and how many we are allowed to take, so as not to break the minimality of the function $f$.
[ "greedy", "number theory" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; k += 1; vector<int> a(n); for (int& x : a) { cin >> x; int cur = 1; while (x--) cur *= 10; x = cur; } long long res = 0; for (int i = 0; i < n; i++) { int cnt = k; if (i + 1 < n) cnt = min(cnt, a[i + 1] / a[i] - 1); res += a[i] * 1LL * cnt; k -= cnt; } cout << res << '\n'; } }
1606
D
Red-Blue Matrix
You are given a matrix, consisting of $n$ rows and $m$ columns. The $j$-th cell of the $i$-th row contains an integer $a_{ij}$. First, you have to color each row of the matrix either red or blue in such a way that \textbf{at least one row is colored red} and \textbf{at least one row is colored blue}. Then, you have to choose an integer $k$ ($1 \le k < m$) and cut the colored matrix in such a way that the first $k$ columns become a separate matrix (the left matrix) and the last $m-k$ columns become a separate matrix (the right matrix). The coloring and the cut are called perfect if two properties hold: - every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; - every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
Imagine you fixed some cut and then colored one row red. Which rows can now be colored red or blue so that the condition on the left matrix is satisfied? If the row has at least one number greater or equal than the numbers in the red row, then the row must be red. Otherwise, it can be either red or blue. However, imagine a weaker condition. Let's look only at the first cell in each row. Sort the rows by the first cell in them. Similarly, if a row is colored red, all the rows that are further in the sorted order should also be red, because they already have a greater or equal number in them. It implies that after you sort the rows, the only possible colorings are: color some prefix of the rows in blue and the remaining suffix in red. So there are $n$ possible colorings and $m$ possible cuts. If we learn to check if they are perfect in $O(1)$, we can get the solution in $O(nm)$. Turns out, the condition "all numbers in the submatrix should be greater than all numbers in the other submatrix" is the same as "the minimum in the first submatrix should be greater than the maximum in the second submatrix". Thus, you can first precalculate prefix and suffix minimums and maximums and check a coloring and a cut in $O(1)$. Overall complexity: $O(n \log n + nm)$ per testcase.
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; int main() { int tc; scanf("%d", &tc); while (tc--){ int n, m; scanf("%d%d", &n, &m); vector<vector<int>> a(n, vector<int>(m)); forn(i, n) forn(j, m) scanf("%d", &a[i][j]); vector<int> ord(n); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&a](int x, int y){ return a[x][0] > a[y][0]; }); vector<vector<int>> mxl(n, vector<int>(m, -INF)); vector<vector<int>> mnr(n, vector<int>(m, INF)); for (int i = n - 1; i >= 0; --i) forn(j, m){ mxl[i][j] = a[ord[i]][j]; if (i < n - 1) mxl[i][j] = max(mxl[i][j], mxl[i + 1][j]); if (j > 0) mxl[i][j] = max(mxl[i][j], mxl[i][j - 1]); } for (int i = n - 1; i >= 0; --i) for (int j = m - 1; j >= 0; --j){ mnr[i][j] = a[ord[i]][j]; if (i < n - 1) mnr[i][j] = min(mnr[i][j], mnr[i + 1][j]); if (j < m - 1) mnr[i][j] = min(mnr[i][j], mnr[i][j + 1]); } vector<int> mnl(m, INF), mxr(m, -INF); pair<int, int> ans(-1, -1); forn(i, n - 1){ forn(j, m){ mnl[j] = min(mnl[j], a[ord[i]][j]); if (j > 0) mnl[j] = min(mnl[j], mnl[j - 1]); } for (int j = m - 1; j >= 0; --j){ mxr[j] = max(mxr[j], a[ord[i]][j]); if (j < m - 1) mxr[j] = max(mxr[j], mxr[j + 1]); } forn(j, m - 1) if (mnl[j] > mxl[i + 1][j] && mxr[j + 1] < mnr[i + 1][j + 1]){ ans = {i, j}; } } if (ans.first == -1){ puts("NO"); continue; } puts("YES"); string res(n, '.'); forn(i, n) res[ord[i]] = i <= ans.first ? 'R' : 'B'; printf("%s %d\n", res.c_str(), ans.second + 1); } return 0; }
1606
E
Arena
There are $n$ heroes fighting in the arena. Initially, the $i$-th hero has $a_i$ health points. The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals $1$ damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than $1$ at the end of the round are considered killed. If exactly $1$ hero remains alive after a certain round, then he is declared the winner. Otherwise, there is no winner. Your task is to calculate the number of ways to choose the initial health points for each hero $a_i$, where $1 \le a_i \le x$, so that there is no winner of the fight. The number of ways can be very large, so print it modulo $998244353$. Two ways are considered different if at least one hero has a different amount of health. For example, $[1, 2, 1]$ and $[2, 1, 1]$ are different.
Let's calculate the following dynamic programming $dp_{i, j}$ - the number of ways to choose the initial health if there are $i$ heroes still alive, and they already received $j$ damage. Let's iterate over $k$ - the number of heroes that will survive after the next round. Then we have to make a transition to the state $dp_{k, nj}$, where $nj = \min(x, j + i - 1)$ (the minimum of the maximum allowed health and $j$ plus the damage done in this round). It remains to understand with what coefficient we should make this transition in dynamic programming. This coefficient is equal to $\binom{i}{i - k} \cdot (nj - j)^{i - k}$ - the number of ways to choose which of the $i$ living heroes will die in this round multiplied by the number of ways to choose health for these $i - k$ heroes (because their health is greater than $j$ so that they are still alive at the moment, but not more than $nj$ so that they are guaranteed to die in this round). Of course, we don't make any transitions from the states $dp_{i,j}$ where $i < 2$, since they represent the fights that have already finished. The answer is the sum of all $dp_{0, j}$ for every $j \in [0, x]$.
[ "combinatorics", "dp", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 505; const int MOD = 998244353; int n, x; int c[N][N], dp[N][N]; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; return x; } int mul(int x, int y) { return x * 1ll * y % MOD; } int main() { cin >> n >> x; for (int i = 0; i <= n; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) c[i][j] = add(c[i - 1][j], c[i - 1][j - 1]); } dp[n][0] = 1; for (int i = n; i > 1; i--) { for (int j = 0; j < x; ++j) { if (!dp[i][j]) continue; int pw = 1, nj = min(x, j + i - 1); for (int k = i; k >= 0; k--) { dp[k][nj] = add(dp[k][nj], mul(dp[i][j], mul(c[i][k], pw))); pw = mul(pw, nj - j); } } } int ans = 0; for (int i = 0; i <= x; ++i) ans = add(ans, dp[0][i]); cout << ans << endl; }
1606
F
Tree Queries
You are given a tree consisting of $n$ vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex $1$. You have to process $q$ queries. In each query, you are given a vertex of the tree $v$ and an integer $k$. To process a query, you may delete any vertices from the tree in any order, except for the root and the vertex $v$. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of $c(v) - m \cdot k$ (where $c(v)$ is the resulting number of children of the vertex $v$, and $m$ is the number of vertices you have deleted). Print the maximum possible value you can obtain. The queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.
A naive solution to this problem would be to implement a recursive function which answers each query: let $f(v, k)$ be the answer to the query "$v$ $k$", we can calculate it as $\sum\limits_{u \in children(v)} \max(1, f(u, k) - k)$, since for each child $u$ of vertex $v$, we either delete it and change the score by $f(u, k) - k$, or choose to let it remain, and this increases the score by $1$. Unfortunately, it is too slow. Let's try to optimize it. First of all, $f(v, k-1) \ge f(v, k)$ since if we choose the exact same subset of vertices to delete for the query "$v$ $k-1$" as we've chosen for the query "$v$ $k$", our score won't decrease. Using this fact, we can show that if it's optimal to remove some vertex in the query "$v$ $k$", it's also optimal to remove a vertex in the query "$v$ $k-1$" because it's optimal to remove vertex $u$ if $f(u, k) - k > 1$, and if this condition holds for some value of $k$, then it holds for each smaller value of $k$. Let $opt(u)$ be the maximum value of $k$ when it's optimal to remove the vertex $u$. We will calculate these values for all vertices of the tree using an event processing method: we'll process the values of $k$ from $200000$ to $0$ and use a set or a priority queue to store events of the form "at the value $i$, vertex $u$ becomes optimal to delete". This set/priority queue should sort the events in descending order of the value of $k$, and in case of ties, in descending order of depths of the vertices (to make sure that vertices with the same value of $opt(u)$ are processed from bottom to up). Let's analyze the implementation of this process more in detail. For each vertex, we will store two values - the number of vertices we should remove from its subtree, and the number of children this vertex will optimally have. Using these two values, we can easily calculate the value of $opt$ for a vertex. When a vertex is "removed" (that is, the event corresponding to this vertex is processed), these values for this vertex should be added to its current parent (we can use DSU to find the current parent easily, for example; and don't forget that the number of vertices we have to remove for this new parent also increases by $1$); then we recalculate the value of $opt$ for the current parent and change the event corresponding to this current parent (note that the value of $opt$ for the current parent shouldn't be greater than the value of $opt$ for the vertex we've deleted). Okay, this allows us to calculate when it's optimal to delete each vertex. But how do we answer queries? One of the ways to do this is to process queries in the same event processing algorithm (and for every value of $k$, we first "remove" the vertices $u$ with $opt(u) = k$, then process the queries). There is an issue that when we remove a vertex, it can affect the answer not only for its current parent, but also for the vertices that could be its parents, but are already deleted; to handle this, instead of adding the values of the deleted vertex only to the values of its current parent, we perform an addition on the whole path from the vertex to the current parent (excluding the vertex itself). This path addition can be performed with a Fenwick or Segment tree over the Eulerian tour of the tree, and this yields a compexity of $O(n \log n)$, though with a high constant factor.
[ "brute force", "dp", "trees" ]
2,800
#include <bits/stdc++.h> using namespace std; struct Vertex { int cost; int depth; int idx; Vertex() {}; Vertex(int cost, int depth, int idx) : cost(cost), depth(depth), idx(idx) {}; }; bool operator <(const Vertex& a, const Vertex& b) { if(a.cost != b.cost) return a.cost > b.cost; if(a.depth != b.depth) return a.depth > b.depth; return a.idx < b.idx; } struct DSU { int n; vector<int> p; vector<int> top; int get(int x) { if(p[x] == x) return x; return p[x] = get(p[x]); } int get_top(int x) { return top[get(x)]; } void merge(int x, int par) { p[x] = par; } DSU(int k = 0) { n = k; p.resize(n); iota(p.begin(), p.end(), 0); top = p; }; }; const int N = 200043; int n; vector<int> g[N]; int p[N], d[N], tin[N], tout[N]; int qv[N]; int qk[N]; int T = 0; void dfs(int v = 0, int par = -1) { tin[v] = T++; p[v] = par; if(par == -1) d[v] = 0; else d[v] = d[par] + 1; for(auto x : g[v]) if(x != par) dfs(x, v); tout[v] = T; } pair<long long, long long> tree[4 * N]; pair<long long, long long> operator+(const pair<long long, long long>& a, const pair<long long, long long>& b) { return make_pair(a.first + b.first, a.second + b.second); } pair<long long, long long> get(int v, int l, int r, int L, int R) { if(L >= R) return {0, 0}; if(l == L && r == R) return tree[v]; int m = (l + r) / 2; return get(v * 2 + 1, l, m, L, min(R, m)) + get(v * 2 + 2, m, r, max(m, L), R); } void add(int v, int l, int r, int pos, pair<long long, long long> val) { if(l == r - 1) tree[v] = tree[v] + val; else { int m = (l + r) / 2; if(pos < m) add(v * 2 + 1, l, m, pos, val); else add(v * 2 + 2, m, r, pos, val); tree[v] = tree[v] + val; } } pair<long long, long long> get_vertex_value(int v) { return get(0, 0, n, tin[v], tout[v]); } void add_on_path(int x, int y, pair<long long, long long> val) { // x is a descendant of y add(0, 0, n, tin[x], val); if(p[y] != -1) add(0, 0, n, tin[p[y]], make_pair(-val.first, -val.second)); } int calculate_cost(int v, int correction) { //cerr << v << " " << correction << endl; pair<long long, long long> res = get_vertex_value(v); // first - (second + 1) * k <= 0 long long k = (res.first + res.second) / (res.second + 1) - 1; if(correction < k) return correction; return k; } int main() { scanf("%d", &n); for(int i = 1; i < n; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; g[x].push_back(y); g[y].push_back(x); } int q; scanf("%d", &q); for(int i = 0; i < q; i++) { scanf("%d %d", &qv[i], &qk[i]); --qv[i]; } dfs(); DSU dsu(n); vector<long long> ans(q); set<Vertex> pq; vector<Vertex> curv(n); for(int i = 0; i < n; i++) { int count_children = g[i].size(); if(i != 0) count_children--; add_on_path(i, i, make_pair((long long)(count_children), 0ll)); if(i != 0) { curv[i] = Vertex(calculate_cost(i, 200000), d[i], i); pq.insert(curv[i]); } } for(int i = 0; i < q; i++) pq.insert(Vertex(qk[i], -1, i)); while(!pq.empty()) { Vertex z = *pq.begin(); pq.erase(pq.begin()); if(z.depth == -1) { auto res = get_vertex_value(qv[z.idx]); ans[z.idx] = res.first - res.second * z.cost; } else { int v = z.idx; int pv = p[v]; int newtop = dsu.get_top(pv); pair<long long, long long> val = get_vertex_value(v); val.second++; val.first--; if(newtop != 0) pq.erase(curv[newtop]); add_on_path(pv, newtop, val); if(newtop != 0) curv[newtop].cost = calculate_cost(newtop, z.cost); if(newtop != 0) pq.insert(curv[newtop]); dsu.merge(v, pv); } } for(int i = 0; i < q; i++) printf("%lld\n", ans[i]); }
1607
A
Linear Keyboard
You are given a keyboard that consists of $26$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter. You have to type the word $s$ on this keyboard. It also consists only of lowercase Latin letters. To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it. Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word. For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $8$, $5$, $12$ and $15$, respectively. Therefore, it will take $|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$ units of time to type the word "hello". Determine how long it will take to print the word $s$.
Since it does not take time to place your hand over the first letter, you need to calculate the sum of the distances between the keyboard keys corresponding to each pair of adjacent letters of the word, that is $\sum\limits_{i=2}^n |\mathtt{pos}(s_i) - \mathtt{pos}(s_{i-1})|$ In order to calculate this sum, let's just iterate through the word $s$ with the for loop and find the differences between the positions of $s_i$ and $s_{i-1}$ on the keyboard. To find the position of a character on the keyboard, you could either use the built-in strings functions (such as str.index in Python or string::find in C++) or precalculate each letter's position on the keyboard into a separate array using another loop over a keyboard.
[ "implementation", "strings" ]
800
t = int(input()) for _ in range(t): k, s = input(), input() res = 0 for i in range(1, len(s)): res += abs(k.index(s[i]) - k.index(s[i - 1])) print(res)
1607
B
Odd Grasshopper
The grasshopper is located on the numeric axis at the point with coordinate $x_0$. Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $x$ with a distance $d$ to the left moves the grasshopper to a point with a coordinate $x - d$, while jumping to the right moves him to a point with a coordinate $x + d$. The grasshopper is very fond of positive integers, so for each integer $i$ starting with $1$ the following holds: exactly $i$ minutes after the start he makes a jump with a distance of exactly $i$. So, in the first minutes he jumps by $1$, then by $2$, and so on. The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an \textbf{even} coordinate, the grasshopper jumps to the \textbf{left}, \textbf{otherwise} he jumps to the \textbf{right}. For example, if after $18$ consecutive jumps he arrives at the point with a coordinate $7$, he will jump by a distance of $19$ to the right, since $7$ is an odd number, and will end up at a point $7 + 19 = 26$. Since $26$ is an even number, the next jump the grasshopper will make to the left by a distance of $20$, and it will move him to the point $26 - 20 = 6$. Find exactly which point the grasshopper will be at after exactly $n$ jumps.
Consider the first four actions that the grasshopper will perform, starting at a point with coordinate $0$: coordinate $0$ is even, jumping left to $1$ leads to $-1$ coordinate $-1$ is odd, jumping right to $2$ leads to $2$ coordinate $1$ is odd, jumping right to $3$ leads to $4$ coordinate $4$ is even, jumping left to $4$ leads to $0$ If you look closely at the next four jumps, they follow the same pattern: jump to the left, two jumps to the right, jump to the left. In general, making jumps with numbers $4k + 1 \ldots 4k + 4$, the grasshopper will start from coordinate $0$ and move as $0 \underset{\ ^{-(4k+1)}}{\longrightarrow} -(4k + 1) \underset{\ ^{+(4k+2)}}{\longrightarrow} 1 \underset{\ ^{+(4k+3)}}{\longrightarrow} 4k + 4 \underset{\ ^{-(4k+4)}}{\longrightarrow} 0$ Thus, if $x_0$ were always zero, the answer would be $-n$ if $n \equiv 1 \bmod 4$ $1$ if $n \equiv 2 \bmod 4$ $n + 1$ if $n \equiv 3 \bmod 4$ $0$ if $n$ is divisible by $4$ Let's find an answer for the cases when $x_0 \neq 0$. But if $x_0$ is even, then all steps will follow the same directions, and the answer will be $x_0 + D$, where $D$ is the answer for the same $n$ and starting point $0$ (described above). And if $x_0$ is odd, then all steps will have opposite directions, and the answer will be $x_0 - D$.
[ "math" ]
900
t = int(input()) maps = [ lambda x: 0, lambda x: x, lambda x: -1, lambda x: -x - 1 ] for _ in range(t): x0, n = map(int, input().split()) d = maps[n % 4](n) print(x0 - d if x0 % 2 == 0 else x0 + d)
1607
C
Minimum Extraction
Yelisey has an array $a$ of $n$ integers. If $a$ has length strictly greater than $1$, then Yelisei can apply an operation called minimum extraction to it: - First, Yelisei finds the minimal number $m$ in the array. If there are several identical minima, Yelisey can choose any of them. - Then the selected minimal element is removed from the array. After that, $m$ is subtracted from each remaining element. Thus, after each operation, the length of the array is reduced by $1$. For example, if $a = [1, 6, -4, -2, -4]$, then the minimum element in it is $a_3 = -4$, which means that after this operation the array will be equal to $a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0]$. Since Yelisey likes big numbers, he wants the numbers in the array $a$ to be as big as possible. Formally speaking, he wants to make the \textbf{minimum} of the numbers in array $a$ to be \textbf{maximal possible} (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length $1$. Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.
Note that the order of numbers in the array does not affect anything. If you swap two elements in the original array, the set of elements at each step will not change in any way. Let's sort the original array $a$ and denote it by $a^0$. We denote by $a^i$ the state of array $a^0$ after applying $i$ operations of minimum extraction. The minimum element in $a^0$ is $a^0_1$, so the elements of array $a^1$ will be equal to $a^1_i = a^0_{i+1} - a^0_1$, and therefore the minimum of them will be $a^0_2 - a^0_1$. Constructing an array $a^2$, we can notice that its elements are equal to $a^2_i = a^1_{i+1} - a^1_1$. We know that the elements of $a^1$ are the difference between corresponding elements of the array $a^0$ and $a^0_1$, so $a^2_i = a^1_{i+1} - a^1_1 = (a^0_{i+2} - a^0_1) - (a^0_2 - a^0_1) = a^0_{i+2} - a^0_2$ Thus, the elements of the array $a^2$ are the differences between elements of $a^0$ starting with third and $a^0_2$, the minimum of which is $a^0_3 - a^0_2$. It is not difficult to show in a similar way (for example by induction) that the elements of $a^c$ are equal to $a^c_i = a^0_{i+c} - a^0_c$, the minimum of which is $a^0_{c+1} - a^0_c$. So the "candidates" for the answer are simply differences of adjacent elements of the array $a^0$. Indeed, if we look at $a^0 = [1, 4, 6, 12, 13]$, it will undergo changes as follows: $[\color{blue}{1}, 4, 6, 12, 15] \to [\color{blue}{3}, 5, 11, 14] \to [\color{blue}{2}, 8, 11] \to [\color{blue}{6}, 9] \to [\color{blue}{3}]$. You can notice that the minimum elements starting with after the first operation are exactly $4 - 1$, $6 - 4$, $12 - 6$ and $15 - 12$, respectively. Thus, to solve the problem, it was sufficient to sort the array in ascending order, then take the maximum of the original first element and the differences of all adjacent elements $\max\left(a^0_1, \max\limits_{i=2}^n \left(a^0_i - a^0_{i-1}\right) \right)$
[ "brute force", "sortings" ]
1,000
t = int(input()) for _ in range(t): n = int(input()) a = sorted(list(map(int, input().split()))) res = a[0] for i in range(n - 1): res = max(res, a[i + 1] - a[i]) print(res)
1607
D
Blue-Red Permutation
You are given an array of integers $a$ of length $n$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: - either you can select any blue element and decrease its value by $1$; - or you can select any red element and increase its value by $1$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable. Determine whether it is possible to make $0$ or more steps such that the resulting array is a permutation of numbers from $1$ to $n$? In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $a$ contains in some order all numbers from $1$ to $n$ (inclusive), each exactly once.
Note the following fact: if a number $x$ in a permutation was obtained from a blue number and a number $y$ in a permutation was obtained from a red number, and $x > y$, then by decreasing the blue number and increasing the red number exactly $x - y$ times each, we will obtain the same permutation in which the two numbers have swapped places. Thus, if a permutation can be obtained at all, some permutation can be obtained by making all the red numbers equal to $n, n - 1, \ldots, n - k + 1$, and the blue ones equal to $1, 2, \ldots, n - k$, where $k$ is the total count of red numbers. Now consider separately two red numbers $a_i$ and $a_j$ such that $a_i > a_j$. If $x$ is produced by increasing $a_i$ and $y$ is produced by increasing $a_j$, and in the same time $x < y$ then $y > x \geqslant a_i > a_j$, and the following is also true: $x > a_j$ and $y > a_i$. So we just showed that if an answer exists, it also exists if greater numbers are produced by greater values from the input. The same holds for the blue numbers. Let us sort all elements $a_i$ by the key $(c_i, a_i)$, where $c_i$ the color of $i$-th element (and blue comes before red). It remains to check that for any $t$ from $1$ to $n$ we can get the number $t$ from the $t$-th element of the obtained sorted array. To do this, we iterate through it and check that either $c_t = \,$'B' and $a_t \geqslant t$ so it can be reduced to $t$, or, symmetrically, $c_t = \,$'R' and $a_t \leqslant t$.
[ "greedy", "math", "sortings" ]
1,300
#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<int> a(n); forn(i, n) cin >> a[i]; string c; cin >> c; vector<int> l, r; forn(i, n) (c[i] == 'B' ? l : r).push_back(a[i]); sort(l.begin(), l.end()); sort(r.begin(), r.end(), greater<int>()); bool ok = true; forn(i, l.size()) if (l[i] < i + 1) ok = false; forn(i, r.size()) if (r[i] > n - i) ok = false; cout << (ok ? "YES" : "NO") << '\n'; } }
1607
E
Robot on the Board 1
The robot is located on a checkered rectangular board of size $n \times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. The sequence of commands $s$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively. The robot can start its movement in \textbf{any} cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $s$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is \textbf{not considered} successfully executed. The robot's task is to execute as many commands as possible without falling off the board. For example, on board $3 \times 3$, if the robot starts a sequence of actions $s=$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $(2, 1)$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $(1, 2)$ (first row, second column). \begin{center} {\small The robot starts from cell $(2, 1)$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $(1, 2)$ (first row, second column).} \end{center} Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
Let's look at the answer $(r, c)$. Let's see how many commands the robot can execute. Since the robot breaks as soon as goes outside the field, if any command causes it to break, it either leads to its total shift relative to $(r, c)$ of exactly $c$ to the left or exactly $m - c + 1$ to the right, or, similarly, of exactly $r$ up or exactly $n - r + 1$ down. Denote by $d[\leftrightarrow]$ and $d[\updownarrow]$ the sum of the maximum positive (right, down) and maximum negative (left, up) shifts in the corresponding direction. By adding up the above constraints, we get the fact that the robot will not fall off the board only if $d[\leftrightarrow] \leqslant (c - 1) + ((m - c + 1) - 1) = m - 1$ and $d[\updownarrow] \leqslant (r - 1) + ((n - r + 1) - 1) = n - 1$. Note that the reverse is also true: if both these conditions are satisfied, then starting from the point $(\max[\leftarrow] + 1, \max[\uparrow] + 1)$ where $\max[\mathtt{dir}]$ is the maximum shift along the direction $\mathtt{dir}$, the robot will not pass any of the board's edges. Thus, it is sufficient to find the number of commands which, when executed, hold the following invariant: $d[\leftrightarrow] \leqslant m - 1 \land d[\updownarrow] \leqslant n - 1$ The horizontal shift can be calculated as the difference between the number of letters 'R' and the number of letters 'L' encountered. Similarly, the vertical shift - as the difference of the numbers of 'D' and 'U'. Let's iterate over the sequence of commands, maintaining relevant values of $\max[\mathtt{dir}]$ for all $\mathtt{dir} \in [\leftarrow, \rightarrow, \uparrow, \downarrow]$. After executing each command, if the robot goes farther in some direction than ever before, we update the corresponding $\max$. Either we reach the end of $s$, or we meet a command after which either $d[\leftrightarrow] = \max[\leftarrow] + \max[\rightarrow]$ becomes equal to $m$, or $d[\updownarrow] = \max[\uparrow] + \max[\downarrow]$ becomes equal to $n$ and the robot breaks, so the previous command was the last one successfully executed. The possible answer is $(\max[\leftarrow] + 1, \max[\uparrow] + 1)$, where the $\max$ values are calculated one command before the robot broke.
[ "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; string s; cin >> s; int bx = 0, by = 0; int min_bx = 0, max_bx = 0, min_by = 0, max_by = 0; for (char c: s) { if (c == 'L') min_by = min(min_by, --by); else if (c == 'R') max_by = max(max_by, ++by); else if (c == 'U') min_bx = min(min_bx, --bx); else max_bx = max(max_bx, ++bx); if (max_bx - min_bx >= n) { if (bx == min_bx) min_bx++; break; } if (max_by - min_by >= m) { if (by == min_by) min_by++; break; } } cout << 1 - min_bx << ' ' << 1 - min_by << '\n'; } }
1607
F
Robot on the Board 2
The robot is located on a checkered rectangular board of size $n \times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively. The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move. - If the robot moves beyond the edge of the board, it falls and breaks. - If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops. Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).
Let's start moving from an arbitrary cell of the table, for example, from $(1, 1)$. Movement from each cell is specified by the direction given in that cell, so you can run a loop with a stopping condition "exit from the board border or get to the already visited cell". Create a separate array $d[r][c]$ - how many commands the robot will execute, starting the movement from the cell $(r, c)$; we will also use it to check whether the cell has already been visited or not (not visited if $d[r][c]$ is not yet positive). Finishing the movement from $(1, 1)$ let's consider two cases. Either we have gone beyond the boundary of the array, then we can say for sure that for the $i$-th cell from the end of the sequence $(r_i, c_i)$ the answer is $d[r_i][c_i] = i$. Or we came to the already visited cell, let it be the $t$-th from the end in our path. Then at the end of the path, there is a cycle of length $t$: starting the movement at any cell of this cycle, the robot will walk exactly $t$ steps until it arrives at the already visited cell. Thus, for $i \leqslant t$ distance will be equal to $d[r_i][c_i] = t$, and for all others it will be, as in the first case, $d[r_i][c_i] = i$. Let us run the same algorithm from the next cell, which we have not yet considered. There will be three cases of robot stopping the execution of the commands: the first two repeat those already considered above, and the third case is that the robot will come to the cell $(r_0, c_0)$ already visited on some of the previous iterations of our algorithm. In this case we know that starting from $(r_0, c_0)$, the robot will make exactly $d[r_0][c_0]$ steps, so for the $i$-th cell from the end on the current path $d[r_i][c_i] = d[r_0][c_0] + i$ will hold. The first two cases are handled completely in the same way as described above. Each of the cases is eventually reduced to another iteration over the cells visited in the current path. Let's visit all the cells in reverse and mark all values of $d$. Such algorithm is enough to repeat until each cell is processed, after which for each cell of the table its $d$ will be known and we'll only have to choose the maximal value of $d[r][c]$ among all $(r, c)$.
[ "brute force", "dfs and similar", "graphs", "implementation" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<string> dir(n); for (int i = 0; i < n; i++) cin >> dir[i]; vector<vi> res(n, vi(m, 0)); int opt = 0, optr = 0, optc = 0; for (int r = 0; r < n; r++) { for (int c = 0; c < m; c++) { if (res[r][c] > 0) continue; int nr = r, nc = c; int depth = 0; vector<pii> path; auto ok = [&n, &m](int row, int col) { return row > -1 && row < n && col > -1 && col < m; }; do { res[nr][nc] = --depth; path.emplace_back(nr, nc); if (dir[nr][nc] == 'L') nc--; else if (dir[nr][nc] == 'R') nc++; else if (dir[nr][nc] == 'U') nr--; else nr++; } while (ok(nr, nc) && res[nr][nc] == 0); int start = 1; if (ok(nr, nc)) { if (res[nr][nc] < 0) { int cycle = res[nr][nc] - depth + 1; for (int i = 0; i < cycle; i++) { auto p = path.back(); path.pop_back(); res[p.first][p.second] = cycle; } } start = res[nr][nc] + 1; } while (!path.empty()) { auto p = path.back(); path.pop_back(); res[p.first][p.second] = start++; } if (res[r][c] > opt) { opt = res[r][c]; optr = r; optc = c; } } } cout << optr + 1 << ' ' << optc + 1 << ' ' << opt << '\n'; } }
1607
G
Banquet Preparations 1
A known chef has prepared $n$ dishes: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat. The banquet organizers estimate the balance of $n$ dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat. Technically, the balance equals to $\left|\sum\limits_{i=1}^n a_i - \sum\limits_{i=1}^n b_i\right|$. The smaller the balance, the better. In order to improve the balance, a taster was invited. He will eat \textbf{exactly} $m$ grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he should eat exactly $m$ grams of each dish in total. Determine how much of what type of food the taster should eat from each dish so that the value of the balance is as minimal as possible. If there are several correct answers, you may choose any of them.
Let's find how much meat and fish a taster can eat at most. Note that a taster can eat no more than $\min(a_i, m)$ of fish from the $i$-th dish (since he can't eat more than $m$ or more than there is at all). Similarly, he can eat no more than $\min(b_i, m)$ of meat. Let's sum the obtained values over all $i$ and denote the resulting sums by $A$ and $B$ -the maximum total amount of fish and meat that can be eaten. Let's denote by balance* $T$ the value $\sum\limits_{i=1}^n a_i - \sum\limits_{i=1}^n b_i$, that is the balance without module. If the taster eats as much fish as possible, he will eat $A$ of fish and $nm - A$ of meat, and change the balance* by $-A + (nm - A) = nm - 2A$. Similarly, if he eats the maximum amount of meat, the balance* will change by $2B - nm$. Note that the taster can achieve any balance* between $2B - nm$ and $nm - 2A$ of the same oddity as both of these numbers. To do this, just take the way of eating the maximum fish and substitute eating a gram of fish for a gram of meat several times. Thus, the final balance $T_\mathtt{res}$ can be found as $\min |x|$ over all $x$ between $T + (2B - nm)$ and $T + (nm - 2A)$ with same oddity. To do this, just check the boundaries of the resulting segment - if they have the same sign, then it's the boundary with the smallest absolute value, otherwise we can take one of the numbers $-1$, $0$, $1$ present in said set (depending on the parity of $nm$). All that remains is to find how much of what type to eat from each dish. Having obtained the answer in the previous paragraph (the final balance), we can reconstruct how much fish and how much meat the taster has to eat to achieve it. The expected amount of fish to be eaten can be found as $e_A = \frac{T + nm - T_\mathtt{res}}{2}$. Note that the taster must eat $\max(m - b_i, 0)$ of fish from the $i$-th dish, since if meat $b_i < m$, then at least $m - b_i$ of fish is guaranteed to be eaten. Let's break down $e_A$ into the sum of $nm - B$ (how much total fish will have to be eaten anyway) and the remaining value $g_A = e_A - (nm - B)$. Let's go through all the dishes and collect the first summand as just the sum of $\max(m - b_i, 0)$ over all $i$, and the second summand with greedy algorithm, each time giving the taster as much fish beyond what he must eat anyway until the sum of such "additions" reaches $g_A$. And knowing for each dish how much fish will be eaten from it, the amount of meat eaten can be calculated by subtracting the fish eaten from $m$.
[ "greedy" ]
2,200
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long ll; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<pii> dishes(n); ll balance = 0; ll max_a = 0, max_b = 0; ll total_eat = static_cast<long long>(n) * m; for (int i = 0; i < n; i++) { cin >> dishes[i].first >> dishes[i].second; balance += dishes[i].first - dishes[i].second; max_a += min(m, dishes[i].first); max_b += min(m, dishes[i].second); } ll max_delta = 2 * max_a - total_eat, min_delta = total_eat - 2 * max_b; ll min_a = total_eat - max_b; ll eat_a; if (balance < 0) { eat_a = min_a; if (balance - min_delta >= 0) eat_a = min(max_a, (total_eat + balance + 1) / 2); } else { eat_a = max_a; if (balance - max_delta <= 0) eat_a = min(max_a, (total_eat + balance + 1) / 2); } ll ans = abs(balance - 2 * eat_a + total_eat); cout << ans << '\n'; ll rest_a = eat_a - min_a; for (int i = 0; i < n; i++) { ll cur_a = 0; if (dishes[i].second < m) cur_a += m - dishes[i].second; ll add = min(rest_a, min(m - cur_a, dishes[i].first - cur_a)); cur_a += add; rest_a -= add; cout << cur_a << ' ' << m - cur_a << '\n'; } } }
1607
H
Banquet Preparations 2
The chef has cooked $n$ dishes yet again: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat. Banquet organizers consider two dishes $i$ and $j$ equal if $a_i=a_j$ and $b_i=b_j$ at the same time. The banquet organizers estimate the variety of $n$ dishes as follows. The variety of a set of dishes is equal to the number of different dishes in it. The \textbf{less} variety is, the \textbf{better}. In order to reduce the variety, a taster was invited. He will eat \textbf{exactly} $m_i$ grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he will eat exactly $m_i$ grams of the $i$-th dish in total. Determine how much of what type of food the taster should eat from each dish so that the value of variety is the minimum possible. If there are several correct answers, you may output any of them.
Note that dishes can become equal if and only if they have equal values of $a_i + b_i - m_i$, that is, how much fish and meat remain in them in total after "tasting". Let's calculate this value for each dish and group all the dishes with equal calculated values. The minimum amount of fish that can remain in the $i$-th dish is $a_i^\mathtt{min} = \max(0, a_i - m_i)$ in case where the maximum possible mass of fish is eaten. Similarly, the maximum amount of fish that can remain is $a_i^\mathtt{max} = a_i + \min(0, b_i - m_i)$ in case where the maximum possible mass of meat is eaten. Consider one of the groups $g$ in which there are all the dishes with equal values $G = a_i + b_i - m_i$. We sill assign each dish a corresponding segment on the coordinate line between $a_i^{\mathtt{min}}$ and $a_i^{\mathtt{max}}$. This segment specifies all possible values of the remaining mass of fish in the dish; any value on it is achievable by replacing eating some mass of fish with the same mass of meat. And since $G$ is common, the same amount of remaining fish will imply the same amount of remaining meat, thus, equality. Let us solve the problem for each group independently. Within a group, the problem is reduced to choosing as few points as possible that "cover" all the segments described in the last paragraph (that is, that there should be a point inside each segment). Each selected point will correspond to the resulting dish, and it being inside a segment will mean that such a resulting dish can be obtained from the corresponding starting one. Such a problem is solved as follows: we choose a segment with the minimal right end; because it must contain at least one chosen point we'll greedily choose it equal to its right end; there's no point in choosing a point to the left from it, since it will not cover more segments than the right end of the segment in question; we'll mark all segments containing this point as covered, and repeat the algorithm for the next unprocessed segment with the minimal right end. For this algorithm, it is sufficient to sort the segments by their right ends within each group and iterate through the segments, greedily selecting points in the manner described above. The set of points obtained at the end will be the answer, and its size and the information about the point selected within each segment should be printed in the output. If for a dish $(a_i, b_i, m_i)$ a point $x$ is chosen inside its corresponding segment, then there should be exactly $x$ of fish left in it, that is, you should output the numbers $a_i - x$ and $m_i - (a_i - x)$ in the answer.
[ "greedy", "sortings", "two pointers" ]
2,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) struct seg { int a, b, m; int index; }; int n, ans; vector<seg> segments; map<int, vector<seg>> diags; void erase(multiset<pair<pair<int,int>, int>>& lr, int l, int r, int index) { pair<pair<int,int>,int> plr = make_pair(make_pair(l, r), index); auto i = lr.find(plr); assert(i != lr.end()); lr.erase(i); } void erase(multiset<pair<pair<int,int>, int>>& lr, multiset<pair<pair<int,int>, int>>& rl, int l, int r, int index) { erase(lr, l, r, index); erase(rl, r, l, index); } map<int, pair<int,int>> dd; void setup_dd(int index, int value) { assert(dd.count(index) == 0); int x = segments[index].a - value; int y = segments[index].m - x; assert(segments[index].a - x >= 0); assert(segments[index].b - y >= 0); assert(x + y == segments[index].m); dd[index] = make_pair(x, y); } int solve(vector<seg> s) { int n = s.size(); multiset<pair<pair<int,int>, int>> lr; multiset<pair<pair<int,int>, int>> rl; forn(i, n) { int min_d = max(s[i].m - s[i].b, 0); int max_d = min(s[i].a, s[i].m); lr.insert(make_pair(make_pair(s[i].a - max_d, s[i].a - min_d), s[i].index)); rl.insert(make_pair(make_pair(s[i].a - min_d, s[i].a - max_d), s[i].index)); } int result = 0; while (!rl.empty()) { result++; auto min_r_iterator = rl.begin(); int r = min_r_iterator->first.first; int l = min_r_iterator->first.second; int index = min_r_iterator->second; erase(lr, rl, l, r, index); setup_dd(index, r); while (!lr.empty()) { auto min_l_iterator = lr.begin(); int ll = min_l_iterator->first.first; int rr = min_l_iterator->first.second; int ii = min_l_iterator->second; if (ll <= r) { erase(lr, rl, ll, rr, ii); setup_dd(ii, r); } else break; } } return result; } int main() { int t; cin >> t; forn(tt, t) { cin >> n; diags.clear(); dd.clear(); segments = vector<seg>(n); forn(i, n) { seg s; s.index = i; cin >> s.a >> s.b >> s.m; diags[s.a + s.b - s.m].push_back(s); segments[i] = s; } int sum = 0; for (auto p: diags) sum += solve(p.second); cout << sum << '\n'; forn(i, n) cout << dd[i].first << " " << dd[i].second << '\n'; } }
1608
A
Find Array
Given $n$, find any array $a_1, a_2, \ldots, a_n$ of integers such that all of the following conditions hold: - $1 \le a_i \le 10^9$ for every $i$ from $1$ to $n$. - $a_1 < a_2 < \ldots <a_n$ - For every $i$ from $2$ to $n$, $a_i$ isn't divisible by $a_{i-1}$ It can be shown that such an array always exists under the constraints of the problem.
Notice that $x$ is never divisible by $x-1$ for $x \geq 3$, so we can output $2, 3, \dots, n, n+1$.
[ "constructive algorithms", "math" ]
800
null
1608
B
Build the Permutation
You are given three integers $n, a, b$. Determine if there exists a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, such that: - There are exactly $a$ integers $i$ with $2 \le i \le n-1$ such that $p_{i-1} < p_i > p_{i+1}$ (in other words, there are exactly $a$ local maximums). - There are exactly $b$ integers $i$ with $2 \le i \le n-1$ such that $p_{i-1} > p_i < p_{i+1}$ (in other words, there are exactly $b$ local minimums). If such permutations exist, find any such permutation.
First, answer does not exists if $a+b+2 > n$. Second, answer exists if and only if $|a-b| \leq 1$. It happens because between every two consecutive local maximums must be exactly one local minimum. And vice versa, between two consecutive minimums must be exactly one maximum. First case gives $b \geq a-1$, second - $a \geq b-1$, both in total gives $a-1 \leq b \leq a+1$. Lets build answer considering $a \geq b$. Otherwise we can build inverse answer: swap $a$ and $b$, and perform replace $p_i = n - p_i + 1$. Lets take $a+b+2$ biggest numbers (i. e. from $n$ downto $n-a-b-1$) and put them consequentially, such numbers on first position and on each second position from first are less then other numbers. It gives that every number, except first and last, are local maximum or local minimum. Rest of the numbers needed to be placed before this sequence in increasing order.
[ "constructive algorithms", "greedy" ]
1,200
null
1608
C
Game Master
$n$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $n-1$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
Let's look at the fights in the reversed order. If player $x$ is the winner, then he won against some player $y$ in the last fight. In $(n-2)$-th fight either $x$ or $y$ won against some player $z$, and so on. We always expand the set by adding a player that can lose against at least one player in the set, so if we can start from $x$ and end up with the set of all players, $x$ can win the tournament. If we construct a directed graph where we add an edge from player $u$ to player $v$ if and only if $u$ can win against $v$ in a fight, the problem is equivalent to finding the set of nodes from which we can reach all the other nodes. To reduce the number of edges to $2n-2$, we can sort players descending by $a_i$ and by $b_i$ and add only edges from $i$-th to $(i+1)$-th player in these orders. Notice that $x$ can win the tournament if and only if there is a path from $x$ to the player with maximum $a_i$. To find the set of such nodes, we can run DFS from the player with maximum $a_i$ on the graph with each edge reversed, or do two pointers technique on arrays of players sorted by $a_i$ and $b_i$.
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
1,700
null
1608
D
Dominoes
You are given $n$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet. The coloring is said to be \textbf{valid} if and only if it is possible to rearrange the dominoes in some order such that for each $1 \le i \le n$ the color of the right cell of the $i$-th domino is different from the color of the left cell of the $((i \bmod n)+1)$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell. Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid). As this number can be very big, output it modulo $998\,244\,353$.
If domino coloring is valid we can split cells into $n$ pairs of cells with opposite colors, so there is exactly $n$ cells of each color. Let $C_B$ and $C_W$ be the number of black and the number of white cells in the input, respectively. If $C_B > n$ or $C_W > n$, then the answer is $0$. Otherwise, the number of colorings with exactly $n$ cells of each color is $\binom{2n - C_W - C_B}{n - C_W}$. Unfortunately, some of these colorings are invalid, so we need to subtract them. If there is at least one completely white or completely black domino we can first rearrange them and easily insert multicolored dominoes in between. If all the dominoes are colored in WB or BW the coloring is valid if and only if all dominoes are colored in the same pattern. We have to subtract the number of colorings where each domino is multicolored and they are not all colored in the same pattern. This can be easily done by finding the number of ways to color each domino in WB or BW, multiplying these numbers and possibly subtracting the cases when all the dominoes are colored in the same pattern.
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
2,400
null
1608
E
The Cells on the Paper
On an endless checkered sheet of paper, $n$ cells are chosen and colored in three colors, where $n$ is divisible by $3$. It turns out that there are exactly $\frac{n}{3}$ marked cells of each of three colors! Find the largest such $k$ that it's possible to choose $\frac{k}{3}$ cells of each color, remove all other marked cells, and then select three rectangles with sides parallel to the grid lines so that the following conditions hold: - No two rectangles can intersect (but they can share a part of the boundary). In other words, the area of intersection of any two of these rectangles must be $0$. - The $i$-th rectangle contains all the chosen cells of the $i$-th color and no chosen cells of other colors, for $i = 1, 2, 3$.
Rectangles in optimal answer always arranged in one of the following ways: horizontally from left to right; divided by <<T>>: first rectangle is upper than second and third, and the second is to the left of the third; rotations of previous ways. Lets consider all four rotations and find best answer for arrangements 1 and 2. Additionally, fix the order of colors, they will be $3!=6$. Arrangement 1 can be found by binary search on $k$. Greedily take $k$ leftmost points of first color and $k$ rightmost points of third. Check if rectangles does not cross and it is enough points of seconds color between rectangles. Arrangement 2 is binary search on $k$ too. Take $k$ uppermost points of first color, in remaining area take $k$ leftmost points of second color, check if is enough points of third color in remaining area. Considering the constant factor, in total solution works in $O(36nlogn)$. Bonus. Task can be solved in $O(36n + nlogn)$. In first, sort all points once by $x$ and once by $y$. Arrangement 1 can be solved by two pointers in $O(n)$. For arrangement 2 let first (upper) rectangle be empty, and all points be divided into two noncrossed rectangles in such way that difference between sizes is minimal possible. Now lets move bottom of first rectangle and remove points of second and third colors from their rectangles keeping difference as minimum as possible. It can be achieved with linked list in $O(n)$.
[ "binary search", "implementation", "sortings" ]
2,800
null
1608
F
MEX counting
For an array $c$ of nonnegative integers, $MEX(c)$ denotes the smallest nonnegative integer that doesn't appear in it. For example, $MEX([0, 1, 3]) = 2$, $MEX([42]) = 0$. You are given integers $n, k$, and an array $[b_1, b_2, \ldots, b_n]$. Find the number of arrays $[a_1, a_2, \ldots, a_n]$, for which the following conditions hold: - $0 \le a_i \le n$ for each $i$ for each $i$ from $1$ to $n$. - $|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k$ for each $i$ from $1$ to $n$. As this number can be very big, output it modulo $998\,244\,353$.
Let's count $dp[pos][mex][big]$ - the number of ways to assign first $pos$ elements in a way that: $|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k$ for each $i$ from $1$ to $pos$. $|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k$ for each $i$ from $1$ to $pos$. $MEX([a_1, a_2, \ldots, a_{pos}]) = mex$ $MEX([a_1, a_2, \ldots, a_{pos}]) = mex$ There are exactly $big$ distinct elements among $a_1, a_2, \ldots, a_{pos}$, which are bigger then $mex$. Let's call them large. There are exactly $big$ distinct elements among $a_1, a_2, \ldots, a_{pos}$, which are bigger then $mex$. Let's call them large. We don't care about the exact values of large elements, we care only about their positions and who of them is equal to who. For example, arrays $[3, 3, 4, 0, 1], [4, 4, 5, 0, 1], [5, 5, 3, 0, 1]$ would all be equivalent. We care about the exact values of all other elements. We don't care about the exact values of large elements, we care only about their positions and who of them is equal to who. For example, arrays $[3, 3, 4, 0, 1], [4, 4, 5, 0, 1], [5, 5, 3, 0, 1]$ would all be equivalent. We care about the exact values of all other elements. We only need to consider at most $2k+1$ possible values of $mex$ for each $pos$. Now, let's learn how to transition from $pos$ to $pos+1$. Let's say that now we are at state $(pos, mex, big)$. Where can we transition after assigning $a_{pos+1}$? There are two cases. $MEX$ doesn't change.It happens when $a_{pos+1} \neq mex$. Then, if $a_{pos+1}$ is among those $big$ large elements or is less than $mex$, the number of large elements won't change. Otherwise, the number of large elements increases by $1$ (but we don't care about its value other than it being bigger than $mex$). So, we need to add $(mex + big)dp[pos][mex][big]$ to $dp[pos][mex][big]$, and $dp[pos][mex][big]$ to $dp[pos][mex][big+1]$. It happens when $a_{pos+1} \neq mex$. Then, if $a_{pos+1}$ is among those $big$ large elements or is less than $mex$, the number of large elements won't change. Otherwise, the number of large elements increases by $1$ (but we don't care about its value other than it being bigger than $mex$). So, we need to add $(mex + big)dp[pos][mex][big]$ to $dp[pos][mex][big]$, and $dp[pos][mex][big]$ to $dp[pos][mex][big+1]$. $MEX$ becomes $mex_1 > mex$.It happens only when $a_{pos+1} = mex$, and all numbers from $mex+1$ to $mex_1-1$ appear among those $big$ large elements. There are $\frac{big!}{(big-(mex_1-mex-1))!}$ ways to choose their positions there, and all of them will stop being large, so there will be only $big - (mex_1 - mex - 1)$ elements remaining. So, we have to add $\frac{big!}{(big-(mex_1-mex-1))!}\cdot dp[pos][mex][big]$ to $dp[pos+1][mex_1][big-(mex_1-mex-1)]$ for all valid $pos, mex, big, mex_1$. It happens only when $a_{pos+1} = mex$, and all numbers from $mex+1$ to $mex_1-1$ appear among those $big$ large elements. There are $\frac{big!}{(big-(mex_1-mex-1))!}$ ways to choose their positions there, and all of them will stop being large, so there will be only $big - (mex_1 - mex - 1)$ elements remaining. So, we have to add $\frac{big!}{(big-(mex_1-mex-1))!}\cdot dp[pos][mex][big]$ to $dp[pos+1][mex_1][big-(mex_1-mex-1)]$ for all valid $pos, mex, big, mex_1$. This already gives $O(n^2k^2)$ solution, as we have $n$ iterations and $O(nk^2)$ transitions on each of them. However, this TLEs. So, let's try to optimize our transitions. We will process cases when $MEX$ doesn't change as before, as it's only $O(nk)$ transitions. So consider only transitions where $MEX$ changes. Note that $mex + big$ increases exactly by one in such transitions. Also note that we have to multiply by $big!$ when number of large elements previously was $big$ and divide by $(big - (mex_1 - mex - 1))!$ when the number of large elements now becomes $big - (mex_1 - mex - 1)$. Then let's only consider states with $mex + big =$ some fixed $T$ for now, then we have transitions of sort $(mex, T-mex) \to (mex_1, T+1-mex_1)$ with coefficients $\frac{(T-mex)!}{(T+1-mex_1)!}$. So, to find what we have to add to $dp[pos+1][mex_1][T+1-mex_1]$, we have to find sum of $dp[pos][mex][T-mex]\cdot (T-mex)!$ over all valid $mex<mex_1$, and to divide this sum by $(T+1-mex_1)!$. This is easy to do with prefix sums. So, the final complexity is $O(n^2k)$.
[ "combinatorics", "dp", "implementation" ]
3,200
null
1608
G
Alphabetic Tree
You are given $m$ strings and a tree on $n$ nodes. Each edge has some letter written on it. You have to answer $q$ queries. Each query is described by $4$ integers $u$, $v$, $l$ and $r$. The answer to the query is the total number of occurrences of $str(u,v)$ in strings with indices from $l$ to $r$. $str(u,v)$ is defined as the string that is made by concatenating letters written on the edges on the shortest path from $u$ to $v$ (in order that they are traversed).
Let's concatenate the $m$ input strings, separated by some character not in the input, into a string $S$, and build the suffix array over it. If we could lexicographically compare $str(u, v)$ to some suffix of $S$, we could use binary search to find the left and right boundary of suffixes that start with $str(u, v)$ in the suffix array. Knowing how to find the longest common prefix of a path in the tree and a suffix of $S$ would help us in comparing them, since we would know the first position where these string differ. Letters on the tree are still unrelated to the letters in concatenated string, so let's append them to $S$ in some helpful way. Let's split the tree into chains using heavy-light decomposition and append the chains and reversed chains to the string $S$. This way every path in the tree can be split into $O(logn)$ parts which are substrings of $S$. Let's build LCP array of $S$ from it's suffix array, and then sparse table over the LCP array, to be able to answer queries for longest common prefix of two suffixes of $S$ in $O(1)$. With such queries we can get longest common prefix of a path and a suffix of $S$ in $O(logn)$ by querying LCP for $O(logn)$ parts of the path and corresponding suffixes of $S$. Now we know how to find the range of suffixes which have $str(u, v)$ as a prefix. Out of these suffixes we have to count only these for which first position belongs to a string with index in the set $\{l, l+1, \dots, r \}$. We can do the counting offline, sweeping through strings from the first to the last and maintaining binary indexed tree over suffix array. In iteration $i$ we store $1$ for suffixes of strings with indices $1, 2, \dots, i$, and $0$ for the rest. A query can be solved by taking the difference of sums on suffix array range in iteration $r$ and in iteration $l-1$. Building suffix array can be done in $O(nlog^2n)$, $O(nlogn)$ or $O(n)$ depending on the chosen algorithm, LCP array can be constructed from the suffix array in $O(n)$ using Kasai's algorithm, while the sparse table construction works in $O(nlogn)$ and uses $O(nlogn)$ memory. Searching for the ranges can be done in $O(qlog^2n)$ as described above, and the last offline sweeping part takes $O((n+q)logn)$ time. The overall time complexity is $O((n+q)log^2n)$, with $O(nlogn)$ memory.
[ "binary search", "data structures", "dfs and similar", "hashing", "string suffix structures", "strings", "trees" ]
3,500
null
1609
A
Divide and Multiply
William has array of $n$ numbers $a_1, a_2, \dots, a_n$. He can perform the following sequence of operations \textbf{any number of times}: - Pick any two items from array $a_i$ and $a_j$, where $a_i$ must be a multiple of $2$ - $a_i = \frac{a_i}{2}$ - $a_j = a_j \cdot 2$ Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.
First we divide all numbers by $2$, while they're divisible and calculate $k$, the number of successful divisions. Next we notice that to maximize the sum we need to multiply $2^k$ by the largest number remaining in the array after the described operations.
[ "greedy", "implementation", "math", "number theory" ]
900
def solve(): n = int(input()) a = list(map(int, input().split(' '))) temp = 1 for i in range(n): while (a[i] % 2 == 0): a[i] //= 2 temp *= 2 a.sort() a[-1] *= temp print(sum(a)) t = int(input()) for i in range(t): solve()
1609
B
William the Vigilant
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment: You are given a string $s$ of length $n$ only consisting of characters "a", "b" and "c". There are $q$ queries of format ($pos, c$), meaning replacing the element of string $s$ at position $pos$ with character $c$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a \textbf{substring}. A valid replacement of a character is replacing it with "a", "b" or "c". A string $x$ is a substring of a string $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Notice that the answer to this problem is the number of substrings "abc" Before starting to process queries let's count the number of substrings "abc" in the initial string. Next, notice that changing a character on position $pos$ can only remove one substring "abc" and add only one substring "abc". To check if either of those changes occurred we only need to look at characters no more than two positions away from $pos$ and see if substring "abc" appeared (or disappeared) there.
[ "implementation", "strings" ]
1,100
def solve(): n, m = map(int, input().split(' ')) a = list(input()) num = 0 for i in range(n - 2): if (''.join(a[i:i + 3]) == 'abc'): num += 1 for i in range(m): index, ch = input().split(' ') index = int(index) - 1 for j in range(max(0, index - 2), index + 1): if (''.join(a[j:j + 3]) == 'abc'): num -= 1 a[index] = ch for j in range(max(0, index - 2), index + 1): if (''.join(a[j:j + 3]) == 'abc'): num += 1 print(num) solve()
1609
C
Complex Market Analysis
While performing complex market analysis William encountered the following problem: For a given array $a$ of size $n$ and a natural number $e$, calculate the number of pairs of natural numbers $(i, k)$ which satisfy the following conditions: - $1 \le i, k$ - $i + e \cdot k \le n$. - Product $a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} $ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.
Note that the product of $n$ natural numbers is a prime number if, and only if, $n - 1$ of these numbers equal to one and one number is prime. Next, let's group all of our numbers into groups which are ones. It's important that these groups are separated by a prime numbers. If the current number is neither a one nor a prime, it means we stop building a group for the current index. Let's say we now have $p$ of these groups, then for each $i < p$ we must add product $p_i \cdot p_{i + 1}$, where $p_i$ is the number of ones in group $i$. Also a group of ones doesn't necessarily have to be connected to the subsequent group of ones, so to get the answer we must take into the account their product with the next prime (if there is one) and the previous prime (if there is one) for this group.
[ "binary search", "dp", "implementation", "number theory", "schedules", "two pointers" ]
1,400
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4") // #pragma GCC optimize("Ofast") // #pragma GCC optimize("unroll-loops") #include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <random> #include <iomanip> #include <queue> #include <bitset> using namespace std; #define sqr(a) ((a)*(a)) #define all(a) (a).begin(), (a).end() #define fast_io ios_base::sync_with_stdio(false); cin.tie(nullptr) #define endl '\n' const int MOD = int(1e9) + 7; const int MAXN = 1123456; bool used[MAXN], prime[MAXN]; long long mainSolve(int n, int k, const vector<int>& isOne, const vector<int>& isPrime) { vector <int> ones; vector <bool> chained(n + 1, false); long long res = 0; for (int i = 1; i <= n; ++i) if (!chained[i]){ ones.clear(); int currentOnes = 0; for (int j = i; j <= n; j += k){ if ((!isOne[j] && !isPrime[j]) || chained[j]) { break; } chained[j] = true; if (isOne[j]) { currentOnes++; } else { ones.push_back(currentOnes); currentOnes = 0; } } if (ones.size() == 0) continue; ones.push_back(currentOnes); for (int j = 0; j < ones.size(); ++j) { res += ones[j]; if (j > 0 && j < ones.size() - 1) { res += ones[j]; } if (j < ones.size() - 1) { res += (long long)(ones[j]) * (long long)(ones[j + 1]); } } } return res; } void solve() { int n, k; cin >> n >> k; vector <int> isOne(n + 1, 0), isPrime(n + 1, 0); for (int i = 1; i <= n; ++i) { int a; cin >> a; if (a == 1) { isOne[i] = 1; } else if (prime[a]) { isPrime[i] = 1; } } cout << mainSolve(n, k, isOne, isPrime) << endl; } void precalc() { for (int i = 2; i < MAXN; ++i) if (!used[i]){ prime[i] = true; for (int j = i; j < MAXN; j += i) { used[j] = true; } } } int main() { // freopen("input.txt", "r", stdin); srand(time(0)); fast_io; precalc(); int tests = 1; cin >> tests; while (tests--) { solve(); } }
1609
D
Social Network
William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies. The conference has $n$ participants, who are initially unfamiliar with each other. William can introduce any two people, $a$ and $b$, who were not familiar before, to each other. William has $d$ conditions, $i$'th of which requires person $x_i$ to have a connection to person $y_i$. Formally, two people $x$ and $y$ have a connection if there is such a chain $p_1=x, p_2, p_3, \dots, p_k=y$ for which for all $i$ from $1$ to $k - 1$ it's true that two people with numbers $p_i$ and $p_{i + 1}$ know each other. For every $i$ ($1 \le i \le d$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $1$ and up to and including $i$ and performed \textbf{exactly} $i$ introductions. The conditions are being checked after William performed $i$ introductions. The answer for each $i$ must be calculated independently. It means that when you compute an answer for $i$, you should assume that no two people have been introduced to each other yet.
Note that the conditions form a collection of disjoint sets. Consider two situations: The next condition connects two previously unconnected sets: then we will simply unite. The next condition connects two previously connected sets: this case allows us to "postpone" an edge to use it as we like. The second observation is that inside a set, the most advantageous construction for us has the shape of a star (a star is a graph, wherefrom one vertex there is an edge to all the others in this set). It remains not to forget about the deferred ribs. We can use them to connect some sets. The most profitable solution would be to connect sets with maximum sizes. The constraints of the problem make it possible to do this by a simple traversal over the sets in the order of sorting by the number of vertices in them. Note that it was possible to solve the problem for more complex constraints using a tree of segments or two set<>, but this was not required in this problem.
[ "dsu", "graphs", "greedy", "implementation", "trees" ]
1,600
#include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <random> #include <iomanip> #include <queue> #include <bitset> using namespace std; #define sqr(a) ((a)*(a)) #define all(a) (a).begin(), (a).end() struct DSU { vector<int> to; vector<int> val; int safeEdges = 0; multiset<int> topVals; multiset<int> tempVals; DSU(int n) { to.resize(n); val.resize(n, 1); for (int i = 0; i < n; ++i) { to[i] = i; tempVals.insert(val[i]); } } int f(int v) { if (v == to[v]) return v; return to[v] = f(to[v]); } bool check(multiset<int>& st, int val) { auto it = st.lower_bound(val); if (it == st.end()) return false; return (*it == val); } void merge(int x, int y) { x = f(x); y = f(y); if (x == y) { ++safeEdges; return; } if (check(tempVals, val[x])) tempVals.erase(tempVals.lower_bound(val[x])); else { sum -= val[x]; topVals.erase(topVals.lower_bound(val[x])); } if (check(tempVals, val[y])) tempVals.erase(tempVals.lower_bound(val[y])); else { sum -= val[y]; topVals.erase(topVals.lower_bound(val[y])); } to[y] = x; val[x] = val[x] + val[y]; tempVals.insert(val[x]); } long long sum = 0; int getAnswer() { while (tempVals.size() && topVals.size() < safeEdges + 1) { sum += (*--tempVals.end()); topVals.insert(*--tempVals.end()); tempVals.erase(--tempVals.end()); } while (tempVals.size() && (*topVals.begin()) < (*--tempVals.end())) { sum -= *topVals.begin(); int temp = *topVals.begin(); topVals.erase(topVals.begin()); tempVals.insert(temp); sum += *--tempVals.end(); topVals.insert(*--tempVals.end()); tempVals.erase(*--tempVals.end()); } return sum - 1; } } ; void solve() { int n, m; cin >> n >> m; DSU dsu(n); for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; --x; --y; dsu.merge(x, y); cout << dsu.getAnswer() << "\n"; } } int main() { int numTests = 1; while (numTests--) { solve(); } }
1609
E
William The Oblivious
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it: You are given a string $s$ of length $n$ only consisting of characters "a", "b" and "c". There are $q$ queries of format ($pos, c$), meaning replacing the element of string $s$ at position $pos$ with character $c$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a \textbf{subsequence}. A valid replacement of a character is replacing it with "a", "b" or "c". A string $x$ is said to be a subsequence of string $y$ if $x$ can be obtained from $y$ by deleting some characters without changing the ordering of the remaining characters.
To solve this problem we will use a segment tree. Let's maintain the following informaton for each segment: $dp_{node, mask}$ stores the minimal number of characters that have to be replaced to make the string only contain subsequences equal to $mask$. Next let's define what $mask$ is. Let the first bit of the mask correspond to subsequence $a$, the second bit correspond to subsequence $b$, the third bit correspond to subsequence $c$, the fourth bit correspond to subsequence $ab$, the fifth bit correspond to subsequence $bc$. Then $mask$ contains those subsequences, which have a number corresponding to the number of 1 bits in them. Let's define the value $merge(leftMask, rightMask)$ as a resulting mask which contains the subsequences from both masks and the subsequences that are created as a result of their merge. Then for a new node $node$ and for all masks $mask$ we can define $dp_{node, mask}$ as the minimal among all values $dp_{leftChild, leftMask} + dp_{rightChild, rightMask}$, where $leftChild$ and $rightChild$ are the left and right child nodes of the $node$ in the segment tree and $leftMask$ and $rightMask$ are masks for which $merge(leftMask, rightMask) = mask$. The final answer is the minimal among all $dp_{1, mask}$.
[ "bitmasks", "data structures", "dp", "matrices" ]
2,400
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4") // #pragma GCC optimize("Ofast") // #pragma GCC optimize("unroll-loops") #include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <random> #include <iomanip> #include <queue> #include <bitset> #include <unordered_map> #include <chrono> #define fi first #define se second #define m_p make_pair #define fast_io ios_base::sync_with_stdio(0); cin.tie(0) using namespace std; typedef long long ll; const int inf = int(1e9); int masksMerge[40][40]; vector <string> bits = {"a", "b", "c", "ab", "bc"}; bool contains(const string& s, const string& sub) { int pos = 0; for (int i = 0; i < s.size(); ++i) { if (pos < sub.size() && s[i] == sub[pos]) pos++; } return pos >= sub.size(); } int totalMask(const vector<string>& firstMask, const vector<string>& secondMask) { int msk = 0; for (const auto& f : firstMask) { for (const auto& s : secondMask) { string merged = f + s; if (contains(merged, "abc")) { return -1; } for (int bit = 0; bit < 5; ++bit) { if (contains(merged, bits[bit])) { msk |= (1 << bit); } } } } return msk; } void precalc() { for (int msk1 = 0; msk1 < 32; ++msk1) { for (int msk2 = 0; msk2 < 32; ++msk2) { vector<string> firstMask, secondMask; for (int i = 0; i < 5; ++i) { if (msk1 & (1 << i)) firstMask.push_back(bits[i]); if (msk2 & (1 << i)) secondMask.push_back(bits[i]); } firstMask.push_back(""); secondMask.push_back(""); int msk = totalMask(firstMask, secondMask); masksMerge[msk1][msk2] = msk; } } } struct Node { vector <int> dp; Node() { dp.resize(40, inf); } }; struct Tree { private: int n; vector<Node> nodes; void merge(int v) { for (int i = 0; i < 32; ++i) nodes[v].dp[i] = inf; for (int msk1 = 0; msk1 < 32; ++msk1) { if (nodes[v * 2].dp[msk1] == inf) continue; for (int msk2 = 0; msk2 < 32; ++msk2) { int newMask = masksMerge[msk1][msk2]; if (newMask != -1) { nodes[v].dp[newMask] = min(nodes[v].dp[newMask], nodes[v * 2].dp[msk1] + nodes[v * 2 + 1].dp[msk2]); } } } } void build(int v, int tl, int tr, const string& s) { if (tl == tr) { int mskPos = int(s[tl - 1] - 'a'); nodes[v].dp[(1 << mskPos)] = 0; nodes[v].dp[0] = 1; return; } int tm = (tl + tr) / 2; build(v * 2, tl, tm, s); build(v * 2 + 1, tm + 1, tr, s); merge(v); } void modify(int v, int tl, int tr, int pos, char val) { if (tl == tr) { for (int i = 0; i < 33; ++i) nodes[v].dp[i] = inf; int mskPos = int(val - 'a'); nodes[v].dp[(1 << mskPos)] = 0; nodes[v].dp[0] = 1; return; } int tm = (tl + tr) / 2; if (pos <= tm) modify(v * 2, tl, tm, pos, val); else modify(v * 2 + 1, tm + 1, tr, pos, val); merge(v); } public: Tree(const string& s) { n = int(s.size()); nodes.resize(4 * n); build(1, 1, n, s); } void update(int pos, char x) { modify(1, 1, n, pos, x); } int get() { int ans = inf; for (int i = 0; i < 32; ++i) { ans = min(ans, nodes[1].dp[i]); } return ans; } }; void solve() { int n, q; cin >> n >> q; string s; cin >> s; Tree tree(s); while (q--) { int pos; char x; cin >> pos >> x; tree.update(pos, x); cout << tree.get() << '\n'; } } int main() { fast_io; precalc(); int t = 1; while(t--) { solve(); } return 0; }
1609
F
Interesting Sections
William has an array of non-negative numbers $a_1, a_2, \dots, a_n$. He wants you to find out how many segments $l \le r$ pass the check. The check is performed in the following manner: - The minimum and maximum numbers are found on the segment of the array starting at $l$ and ending at $r$. - The check is considered to be passed if the binary representation of the minimum and maximum numbers have the same number of bits equal to 1.
We will use Divide & Conquer algorithm. Let $f(l, r)$ be the answer to the problem on the subsegment $l\ldots r$. Let's notice, that if $l = r$, then $f(l, r) = 1$, otherwise $f(l, r) = f(l, m) + f(m + 1, r) + f'(l, r)$, where $m = \frac{r + l}{2}$ and $f'(l, r)$ equals to the number of subsegments passing the check, which have left bound ranged from $l$ to $m$ (inclusively) and right bound ranged from $m+1$ to $r$ (inclusively). Let's see how to calculate $f'(l, r)$. Let $max(l, r)$ be equal to maximum on the subsegment $l \ldots r$ and $min(l, r)$ be equal to minimum on the subsegment $l \ldots r$. Let's suppose that the maximal value of the chosen segment is in the left half (the case when the maximal value is in the right half is similar to this one). Now, let's iterate over the left bound $L$ of the segment, maintaining a maximal value of numbers in the left half (in other words, a maximal value on the segment $L\ldots m$). If we iterate over possible $L$-s in descending order, it is possible to maintain a pointer at all possible right bounds in the right half (notice that we want to maintain the greatest $R\_{max}$ such that $max(m + 1, R\_{max}) \le max(L, m)$). Now that we know the maximum, we know the number of bits equal to $1$ that binary representations of maximum and minimum contain. It's only left to find the number of right bounds $R'$ such that: $m + 1 \le R' \le R\_{max}$ $min(L, R')$ has the same number of bits equal to $1$ as $max(L, m)$. For every prefix of the right half let's calculate the minimum on it, in other words, $min(m + 1, pref)$, for every $pref$ such that $m + 1 \le pref \le r$. Notice that we can maintain an array $cnt_x$, which for every $x$ stores the number of right bounds, for which the binary representation of prefix minimum has exactly $x$ bits equal to $1$. The only case left unconsidered is when the minimum is in the left half. Let's notice that if we iterate over $L$-s in descending order, we don't increase the minimum in the left half, which means that we can create a pointer for it in the right half, maintaining such minimal $R\_{min}$, that $min(m + 1, R\_{min}) \le min(L, m)$. It turns out that $R\_{min} - (m + 1)$ segments have maximum and minimum in the left half, and we know how to find those segments, and we just need to check if the binary representations of maximum and minimum of such segments have equal numbers of bits equal to $1$. In all other cases we want to calculate the number of right bounds on the segment $R\_{min}\ldots R\_{max}$, for which the prefix minimum has the same number of bits equal to $1$ as $max(L, m)$. It can be done if we maintain the array $cnt_x$ for the subsegment $R\_{min} \ldots R\_{max}$. If we initially calculate the number of bits equal to $1$ for every number, then we will get a solution in $O(n \cdot \log n + n \cdot \log max\_a)$. 1609G - A Stroll Around the Matrix
[ "data structures", "divide and conquer", "meet-in-the-middle", "two pointers" ]
2,800
null
1609
G
A Stroll Around the Matrix
William has two arrays of numbers $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_m$. The arrays satisfy the conditions of being convex. Formally an array $c$ of length $k$ is considered convex if $c_i - c_{i - 1} < c_{i + 1} - c_i$ for all $i$ from $2$ to $k - 1$ and $c_1 < c_2$. Throughout William's life he observed $q$ changes of two types happening to the arrays: - Add the arithmetic progression $d, d \cdot 2, d \cdot 3, \dots, d \cdot k$ to the suffix of the array $a$ of length $k$. The array after the change looks like this: $[a_1, a_2, \dots, a_{n - k}, a_{n - k + 1} + d, a_{n - k + 2} + d \cdot 2, \dots, a_n + d \cdot k]$. - The same operation, but for array $b$. After each change a matrix $d$ is created from arrays $a$ and $b$, of size $n \times m$, where $d_{i, j}=a_i + b_j$. William wants to get from cell ($1, 1$) to cell ($n, m$) of this matrix. From cell ($x, y$) he can only move to cells ($x + 1, y$) and ($x, y + 1$). The length of a path is calculated as the sum of numbers in cells visited by William, including the first and the last cells. After each change William wants you to help find out the minimal length of the path he could take.
Let's try to solve the problem without asking for changes. Note that in the matrix constructed in this way for the move from (i, j) it is always profitable to go to the cell with the smallest number. This can be seen more clearly in the matrix of the first test case: This allows you to solve the problem with complexity $O(n + m)$, but this is not enough for a complete solution. Let's introduce two new arrays of the difference between the adjacent elements of the arrays $da_i = a_{i + 1} - a_i$ and $db_i = b_{i + 1} - b_i$. Note that our greedy decision turns right out of the cell $(i, j)$, when $da_i > db_j$. For clarity, below is an illustration of the turns: Each time such a turn to the right in the cell $(i, j)$ decreases our total sum by $(da_i - db_j) + (da_{i + 1} - db_j) + \dots + (da_{n - 1} - db_j) = (\sum_{t=i}^{n - 1} da_t) - db_j \cdot (n - i)$. Which is actually equivalent to the sum of $da_i - db_j$ for all $da_i > db_j$. Such a sum can be considered by recognizing for each $i$ by a binary search the last $db_j$ for which the expression $da_i> db_j$ is true. This allows us to solve the problem in $O(n \cdot log(m))$ using the prefix sums of the $db$ array. Now let's get back to change requests. Because the size of the $da$ array is small enough, then we can change the values of its elements by a simple. To store the $db$ array, you will need to use a segment tree supporting the following operations: - Adding a number at the suffix (since we are working with an array $db$, not $b$, then all elements will change by one number equal to the step of the arithmetic progression). - Sum of array numbers on array prefix so far $element_i < X$. ($da_i$ will act as $X$).
[ "data structures", "greedy", "math" ]
3,000
null
1609
H
Pushing Robots
There're $n$ robots placed on a number line. Initially, $i$-th of them occupies unit segment $[x_i, x_i + 1]$. Each robot has a program, consisting of $k$ instructions numbered from $1$ to $k$. The robot performs instructions in a cycle. Each instruction is described by an integer number. Let's denote the number corresponding to the $j$-th instruction of the $i$-th robot as $f_{i, j}$. Initial placement of robots corresponds to the moment of time $0$. During one second from moment of time $t$ ($0 \le t$) until $t + 1$ the following process occurs: - Each robot performs $(t \bmod k + 1)$-th instruction from its list of instructions. Robot number $i$ takes number $F = f_{i, (t \bmod k + 1)}$. If this number is negative (less than zero), the robot is trying to move to the left with force $|F|$. If the number is positive (more than zero), the robot is trying to move to the right with force $F$. Otherwise, the robot does nothing. - Let's imaginary divide robots into groups of consecutive, using the following algorithm: - Initially, each robot belongs to its own group. - Let's sum up numbers corresponding to the instructions of the robots from one group. Note that we are summing numbers without taking them by absolute value. Denote this sum as $S$. We say that the whole group moves together, and does it with force $S$ by the same rules as a single robot. That is if $S$ is negative, the group is trying to move to the left with force $|S|$. If $S$ is positive, the group is trying to move to the right with force $S$. Otherwise, the group does nothing. - If one group is trying to move, and in the direction of movement touches another group, let's unite them. One group is touching another if their outermost robots occupy adjacent unit segments. - Continue this process until groups stop uniting. - Each robot moves by $1$ in the direction of movement of its group or stays in place if its group isn't moving. But there's one exception. - The exception is if there're two groups of robots, divided by exactly one unit segment, such that the left group is trying to move to the right and the right group is trying to move to the left. Let's denote sum in the left group as $S_l$ and sum in the right group as $S_r$. If $|S_l| \le |S_r|$ only the right group will move. Otherwise, only the left group will move. - Note that robots from one group don't glue together. They may separate in the future. The division into groups is imaginary and is needed only to understand how robots will move during one second $[t, t + 1]$. An illustration of the process happening during one second: Rectangles represent robots. Numbers inside rectangles correspond to instructions of robots. The final division into groups is marked with arcs. Below are the positions of the robots after moving. Only the left of the two rightmost groups moved. That's because these two groups tried to move towards each other, and were separated by exactly one unit segment. Look at the examples for a better understanding of the process. You need to answer several questions. What is the position of $a_i$-th robot at the moment of time $t_i$?
First of all, it should be noted, that one iteration of the described algorithm of robots' movements can be implemented in $O(n)$ time. For example, using stack. Let's consider moments of time that are multiple of $k$. And segments of time between such two consecutive moments of time. Consider two adjacent robots. It can be proved that if these two robots touched each other during a segment of time $[k \cdot t, k \cdot (t + 1)]$ ($1 < t$), then they will touch each other during any succeeding segment of time $[k \cdot t', k \cdot (t' + 1)]$ ($t < t'$). One thing that may change in the future is that the left robot will be blocked from moving to the left, or the right robot will be blocked from moving to the right. Robots just will become closer to each other after such a change. It's also possible that the left robot will be blocked from moving to the right, or the right robot from moving to the left. But then they are touching. Similarly, if after $k$ seconds distance between two robots decreases, then it will continue decreasing until they touch during some segment of time. And if two robots touch during a segment of time, then the distance between them after this segment of time will be less than or equal to the distance between them before this segment. Let's simulate the first $k$ seconds, and then another $k$ seconds. Let's look at pairs of adjacent robots. If the distance between two robots increased or didn't change, skip this pair. If the distance between two robots decreased. If the distance is $\le k \cdot 2 + 1$, then robots may touch during the next segment. So, let's simulate the next $k$ seconds again. Otherwise, let distance be $d$ and it decreased by $s$ during the last segment of time. Then, during the next $\lfloor\frac{d - k \cdot 2 - 1}{s}\rfloor$ segments of time it will continue decreasing with the same speed ($s$ units per $k$ seconds). So we can skip these segments of time, and simulate the next after them. If the distance is $\le k \cdot 2 + 1$, then robots may touch during the next segment. So, let's simulate the next $k$ seconds again. Otherwise, let distance be $d$ and it decreased by $s$ during the last segment of time. Then, during the next $\lfloor\frac{d - k \cdot 2 - 1}{s}\rfloor$ segments of time it will continue decreasing with the same speed ($s$ units per $k$ seconds). So we can skip these segments of time, and simulate the next after them. Let's choose the minimum segment of time that should be simulated. Let's skip all till this segment of time, and simulate it. Then again choose the minimum segment of time till which we can skip simulation. It can be proved that there will be simulated $O(n \cdot k)$ segments of time overall. This is due to the fact that there're no more than $O(k)$ decreases of the distance between two adjacent robots, after which we will do the simulation. In order to answer questions, let's also simulate segments of time that contain moments of time of questions. Total time complexity is $O(n \cdot k \cdot (n \cdot k + q))$.
[]
3,500
null
1610
A
Anti Light's Cell Guessing
You are playing a game on a $n \times m$ grid, in which the computer has selected some cell $(x, y)$ of the grid, and you have to determine which one. To do so, you will choose some $k$ and some $k$ cells $(x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)$, and give them to the computer. In response, you will get $k$ numbers $b_1,\, b_2, \ldots b_k$, where $b_i$ is the manhattan distance from $(x_i, y_i)$ to the hidden cell $(x, y)$ (so you know which distance corresponds to which of $k$ input cells). After receiving these $b_1,\, b_2, \ldots, b_k$, you have to be able to determine the hidden cell. What is the smallest $k$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses? As a reminder, the manhattan distance between cells $(a_1, b_1)$ and $(a_2, b_2)$ is equal to $|a_1-a_2|+|b_1-b_2|$.
$\mathcal Complete\;\mathcal Solution$: $\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Let's say the answer is $ans$. If $n == 1$ and $m == 1$, then there's only one cell, so we don't need any more information, and the hidden cell is that single cell. So for this scenario $ans = 0$. If exactly one of $n$ or $m$ equals $1$, then it's trivial that the answer is greater than $0$. Also if we choose the cell $(1, 1)$, we can find the hidden cell. So for this case $ans = 1$. Now assume $2 \le n$ and $2 \le m$, if you choose $(1, 1)$ and $(n, 1)$ then let's say the distance from $(1, 1)$ to the hidden cell is $b_1$ and the distance from $(n, 1)$ to the hidden cell is $b_2$. Then if the hidden cell is $(i, j)$ then $b_1 = i-1 + j-1$ and $b_2 = n-i + j-1$ so $b_1+b_2 = n-1 + 2j-2$ so we can find $j$. After finding $j$ we can find $i$ using $b_1 = i-1+j-1$. So the answer is at most $2$. Now we proof $2 \le ans$, trivially $0 < ans$, but why $ans \ne 1$?. Assume someone chose a cell $(i, j)$ and they could distinguish all the $n \cdot m$ possible hidden cells. It's easy to see that at least $3$ of the $4$ cells $(i, j-1)$, $(i+1, j)$, $(i-1, j)$ and $(i, j+1)$ exist in the table, but their distance from $(i, j)$ is $1$ for all $4$ of them, so we can't distinguish them, so $ans = 2$. Time complexity: $\mathcal{O}(1)$
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, m; cin >> n >> m; if(n == 1 && m == 1){ cout << "0\n"; } else if(min(n, m) == 1){ cout << "1\n"; } else cout << "2\n"; } }
1610
B
Kalindrome Array
An array $[b_1, b_2, \ldots, b_m]$ is a palindrome, if $b_i = b_{m+1-i}$ for each $i$ from $1$ to $m$. Empty array is also a palindrome. An array is called \textbf{kalindrome}, if the following condition holds: - It's possible to select some integer $x$ and delete some of the elements of the array equal to $x$, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to $x$, and you don't have to delete at least one element equal to $x$. For example : - $[1, 2, 1]$ is kalindrome because you can simply not delete a single element. - $[3, 1, 2, 3, 1]$ is kalindrome because you can choose $x = 3$ and delete both elements equal to $3$, obtaining array $[1, 2, 1]$, which is a palindrome. - $[1, 2, 3]$ is not kalindrome. You are given an array $[a_1, a_2, \ldots, a_n]$. Determine if $a$ is kalindrome or not.
If the array is already a palindrome the answer is Yes. Otherwise, let's find the minimum $i$ that $a_i \neq a_{n + 1 - i}$. We can prove that we have to remove either $a_i$ or $a_{n + 1 - i}$ in order the make the array palindrome. Imagine it's possible to make the array palindrome by removing all appearances of $x$. $x \neq a_i, a_{n + 1 - i}$ The number of appearances of $x$ before $i$ is equal to the number of appearances of $x$ after $n + 1 - i$. So in order to make the array palindrome, $a_i$ must be equal to $a_{n + 1 - i}$. So we just have to check if the array will be palindrome after removing all appearances of $a_i$ or after removing all appearances of $a_{n + 1 - i}$. Time complexity: $\mathcal{O}(n)$
[ "greedy", "two pointers" ]
1,100
//khodaya khodet komak kon # include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; typedef pair <pii, int> ppi; typedef pair <int, pii> pip; typedef pair <pii, pii> ppp; typedef pair <ll, ll> pll; # define A first # define B second # define endl '\n' # define sep ' ' # define all(x) x.begin(), x.end() # define kill(x) return cout << x << endl, 0 # define SZ(x) int(x.size()) # define lc id << 1 # define rc id << 1 | 1 # define fast_io ios::sync_with_stdio(0);cin.tie(0); cout.tie(0); ll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));} const int xn = 2e5 + 10; const int xm = - 20 + 10; const int sq = 320; const int inf = 1e9 + 10; const ll INF = 1e18 + 10; const ld eps = 1e-15; const int mod = 998244353; const int base = 257; int qq, n, m, a[xn], b[xn]; bool ans; void check(int x){ m = 0; for (int i = 1; i <= n; ++ i) if (a[i] != x) b[++ m] = a[i]; for (int i = 1; i <= m; ++ i) if (b[i] != b[m + 1 - i]) return; ans = true; } int main(){ fast_io; cin >> qq; while (qq --){ cin >> n, ans = true; for (int i = 1; i <= n; ++ i) cin >> a[i]; for (int i = 1; i <= n; ++ i){ if (a[i] != a[n + 1 - i]){ ans = false; check(a[i]); check(a[n + 1 - i]); break; } } if (ans) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1610
C
Keshi Is Throwing a Party
Keshi is throwing a party and he wants everybody in the party to be happy. He has $n$ friends. His $i$-th friend has $i$ dollars. If you invite the $i$-th friend to the party, he will be happy only if at most $a_i$ people in the party are strictly richer than him and at most $b_i$ people are strictly poorer than him. Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.
Take a look at this greedy approach. Let $p_i$ be the $i$-th poorest invited person.($p_i < p_{i + 1}$) Find the poorest person $v$ that $x - 1 - a_v \le 0 \le b_v$. We will invite this person so $p_1 = v$. For each $2 \le i \le x$ find the poorest person $v$ that $v > p_{i - 1}$ and $x - 1 - a_v \le i - 1 \le b_v$ this means that person $v$ can be the $i$-th poorest invited person. Imagine we fail to find $x$ people but there is a way to do so. The solution chooses $s_1, s_2, \ldots, s_x$. for each $i$ we chose the minimum $p_i$ possible, therefor $p_i \le s_i$. But if our algorithm fails there must exist an index $i$ that $p_i > s_i$. So our algorithm is correct. Time complexity: $\mathcal{O}(n\log n)$
[ "binary search", "greedy" ]
1,600
//In the name of God #include <bits/stdc++.h> using namespace std; typedef int ll; typedef pair<ll, ll> pll; const ll maxn = 2e5 + 100; const ll mod = 1e9 + 7; const ll inf = 1e9; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define file_io freopen("input.txt", "r+", stdin);freopen("output.txt", "w+", stdout); #define pb push_back #define Mp make_pair #define F first #define S second #define Sz(x) ll((x).size()) #define all(x) (x).begin(), (x).end() ll q, n, a[maxn], b[maxn]; bool ok(ll x){ ll c = 0; for(ll i = 0; i < n; i++){ if(x - 1 - a[i] <= c && c <= b[i]) c++; } return c >= x; } int main(){ fast_io; cin >> q; while(q--){ cin >> n; for(ll i = 0; i < n; i++){ cin >> a[i] >> b[i]; } ll l = -1, r = n + 1, mid; while(r - l > 1){ mid = (l + r) >> 1; if(ok(mid)) l = mid; else r = mid; } cout << l << "\n"; } return 0; }
1610
D
Not Quite Lee
Lee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares. A non-empty array $b_1, b_2, \ldots, b_m$ is called \textbf{good}, if there exist $m$ integer sequences which satisfy the following properties: - The $i$-th sequence consists of $b_i$ consecutive integers (for example if $b_i = 3$ then the $i$-th sequence can be $(-1, 0, 1)$ or $(-5, -4, -3)$ but not $(0, -1, 1)$ or $(1, 2, 3, 4)$). - Assuming the sum of integers in the $i$-th sequence is $sum_i$, we want $sum_1 + sum_2 + \ldots + sum_m$ to be equal to $0$. You are given an array $a_1, a_2, \ldots, a_n$. It has $2^n - 1$ nonempty subsequences. Find how many of them are \textbf{good}. As this number can be very large, output it modulo $10^9 + 7$. An array $c$ is a subsequence of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements.
$\mathcal Complete\;\mathcal Solution$: $\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Assume we have an array $c$ of length $k$, need to know if it's good or not. We can choose an initial sequence $t_i$ for all $1 \le i \le k$, then slide them (in other words, choose an index $i$ and increase or decrease all the elements in the $i$-th sequence, keep doing this as many times as you need) that way we can reach any other possible set of sequences that satisfy the first property, so it doesn't matter what we choose as initial sequences, because from any set of $k$ sequences that satisfy the first property, we can reach any other such set of $k$ sequences. After that, if $\displaystyle \sum_{i = 1}^k sum_i = s$, we want to find such $x_i$-s that $\displaystyle \sum_{i=1}^kx_ic_i = -su$ so after sliding $i$-th sequence $|x_i|$ times to the right(or left if $x_i$ is negative) for all $i$, we will have a set of sequences that satisfy both the properties. Now to do that, one can prove if $\displaystyle gcd(c_1, c_2, \ldots, c_k) = g$, then if $g$ divides $s$, the array is good, otherwise it's not (I won't prove it because it's quite well-known and easy). If we choose the initial sequences such that the $i$-th sequence starts from $0$ and ends with $c_i-1$, then $\displaystyle s = \sum_{i=1}^k \frac{c_i(c_i-1)}2$. Now we want $g$ to divide $s$. If $g$ is odd, then it will always divide $s$ because it divides $\frac{c_i}2$. From now on we assume $g$ to be even. One can prove that if $2^l$ divides $g$ and $0 < l$ is maximum such integer, then $\frac g{2^l}$ (which is odd) divides all $\frac{c_i}2$, so $s$ is divisible by $\frac g{2^l}$. So we should only check if $2^l$ also divides $s$ or not. If $2^{l+1}$ divides some $c_i$, then $2^l$ divides $\frac{c_i(c_i-1)}2$ for that $i$ as well. Also if $2^{l+1}$ doesn't divide $c_i$, we knew that $2^l$ divides $c_i$ (because $2^l$ divides $g$ and $g$ divides $c_i$) so $2^{l-1}$ divides $\frac{c_i}2$ but $2^l$ doesn't, also $c_i-1$ is odd. So $\frac{c_i(c_i-1)}2$ has a reminder equal to $2^{l-1}$ modulo $2^l$. All the other terms $\frac{c_i(c_i-1)}2$ were divisible by $2^l$ except these, so if the number of such $c_i$-s is even, then their reminders sum up to $0$ modulo $2^l$ then $c$ is good, and not otherwise. To solve the actual problem, we can fix $l$, maximum power of 2 that divides $g$, now we only care about how many $c_i$-s are divisible by $2^l$ (let's say $x$ such $c_i$-s, also if $x < 2$ then we should skip this $l$ because we need at least $2$ such $c_i$-s to have an array with that $l$), and how many are divisible by $2^{l+1}$ (let's say $y$ such $c_i$-s). Now there are $2^x$ possible subsequences such that $2^l$ divides $g$ (including the empty subsequence), but some of them may have an odd number of $c_i$-s not divisible by $2^{l+1}$, it's easy to see that half of them have an even number of such $c_i$-s, still, for $2^y$ of them, $2^{l+1}$ divides $g$ as well (which is not what we want. Also includes the empty subsequence). So we have $2^{x-1}-2^y$ subsequences with that $l$ (doesn't include the empty subsequence). Then we sum up this for all possible $l$, also don't forget to count $l=0$ separately (i.e. $g$ is odd). Time complexity: $\mathcal{O}(nlog(10^9))$
[ "combinatorics", "dp", "math", "number theory" ]
2,000
//In The Name of God //I usually forget about the previous line... #include <bits/stdc++.h> #define IOS ios::sync_with_stdio(0), cin.tie(), cout.tie(); using namespace std; typedef long long ll; const int maxBt = 30; const int mod = 1e9+7; int cnt[maxBt]; int slv(){ int n; cin >> n; int a[n]; for(int i = 0; i < n; i++){ cin >> a[i]; } int to[n+1]; //powers of 2 to[0] = 1; for(int i = 1; i <= n; i++){ to[i] = to[i-1]*2 % mod; } for(int i = 0; i < n; i++){ int x = 0; for(int k = 0; k < maxBt; k++){ if(a[i] & 1)break; a[i] >>= 1; x++; } cnt[x]++; } int ans = to[n] - to[n-cnt[0]] + mod; if(ans >= mod)ans -= mod; int y = n-cnt[0]; for(int l = 1; l < maxBt; l++){ int x = y; y -= cnt[l]; if(x-y < 2)continue; int delta = to[x-1]-to[y]+mod; if(delta >= mod)delta -= mod; ans += delta; if(ans >= mod)ans -= mod; } return ans; } signed main(){ IOS cout << slv() << '\n'; }
1610
E
AmShZ and G.O.A.T.
Let's call an array of $k$ integers $c_1, c_2, \ldots, c_k$ \textbf{terrible}, if the following condition holds: - Let $AVG$ be the $\frac{c_1 + c_2 + \ldots + c_k}{k}$(the average of all the elements of the array, it doesn't have to be integer). Then the number of elements of the array which are bigger than $AVG$ should be \textbf{strictly} larger than the number of elements of the array which are smaller than $AVG$. Note that elements equal to $AVG$ don't count. For example $c = \{1, 4, 4, 5, 6\}$ is \textbf{terrible} because $AVG = 4.0$ and $5$-th and $4$-th elements are greater than $AVG$ and $1$-st element is smaller than $AVG$. Let's call an array of $m$ integers $b_1, b_2, \ldots, b_m$ \textbf{bad}, if at least one of its non-empty subsequences is terrible, and \textbf{good} otherwise. You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$. Find the minimum number of elements that you have to delete from it to obtain a \textbf{good} array. An array is a subsequence of another array if it can be obtained from it by deletion of several (possibly, zero or all) elements.
We build the longest good subsequence starting with $a_s$ greedily step by step. In each step we add the smallest possible element to the subsequence. If the last element is $a_k$, we have to find the minimum $i$ that $i > k$ and $a_i \ge 2 \cdot a_k - a_s$. (using lower_bound) Assume $b_1 \neq b_2$, then $k < \log(a_n))$. Because for each $i$, $b_{i + 1} \ge 2 \cdot b_i - b_1$ then $b_{i + 1} - b_1 \ge 2 \cdot b_i - 2 \cdot b_1$ then $b_{i + 1} - b_1 \ge 2 \cdot (b_i - b_1)$. And for cases that $b_1 = b_2$, $+ cnt_i$. ($cnt_i$ being the number of occurrences of element $i$) So for each $i$ that $a_i \neq a_{i - 1}$ we do the above greedy approach. We don't need to do it for indices that $a_i = a_{i - 1}$ since adding $a_{i - 1}$ to the longest subsequence starting from $a_i$ doesn't make it bad. Time complexity is $\log(n) \cdot \displaystyle\sum_{a_i \neq a_{i - 1}}{cnt_i + \log(a_n)} \le \log(n) \cdot \left( n \cdot \log(a_n) + \displaystyle\sum_{a_i \neq a_{i - 1}}{cnt_i} \right) \le \log(n) \cdot (n \cdot \log(a_n) + n)$. The overall time complexity will be $\mathcal{O}(n \cdot \log n \cdot \log a_n)$
[ "binary search", "brute force", "greedy", "implementation", "math" ]
2,300
//khodaya khodet komak kon # include <bits/stdc++.h> using namespace std; const int xn = 2e5 + 10; int qq, n, a[xn], ans, res, ptr; int main(){ ios::sync_with_stdio(0);cin.tie(0); cout.tie(0); cin >> qq; while (qq --){ cin >> n, ans = 0; for (int i = 1; i <= n; ++ i) cin >> a[i]; for (int i = 1; i <= n; ++ i){ if (a[i] == a[i - 1]) continue; res = 0, ptr = i; while (ptr <= n) ptr = lower_bound(a + ptr + 1, a + n + 1, 2 * a[ptr] - a[i]) - a, ++ res; ans = max(ans, res); } cout << n - ans << "\n"; } return 0; }
1610
F
Mashtali: a Space Oddysey
Lee was planning to get closer to Mashtali's heart to proceed with his evil plan(which we're not aware of, yet), so he decided to beautify Mashtali's graph. But he made several rules for himself. And also he was too busy with his plans that he didn't have time for such minor tasks, so he asked you for help. Mashtali's graph is an \textbf{undirected} weighted graph with $n$ vertices and $m$ edges with weights equal to either $1$ or $2$. Lee wants to direct the edges of Mashtali's graph so that it will be as beautiful as possible. Lee thinks that the beauty of a directed weighted graph is equal to the number of its Oddysey vertices. A vertex $v$ is an Oddysey vertex if $|d^+(v) - d^-(v)| = 1$, where $d^+(v)$ is the sum of weights of the outgoing from $v$ edges, and $d^-(v)$ is the sum of the weights of the incoming to $v$ edges. Find the largest possible beauty of a graph that Lee can achieve by directing the edges of Mashtali's graph. In addition, find any way to achieve it. Note that you have to orient each edge.
If there is a vertex $v$ connected to its neighbors $x$ and $y$ with same edge weights, we delete these edges and add a new edge between $x$ and $y$. So the number of edges decreases by 1. Now we solve the problem for our new graph recurrently. Then we check whether the assigned direction is from $x$ to $y$ or from $y$ to $x$. In the first case, we should delete this edge and add a directional edge from $x$ to $v$ and from $v$ to $y$. Otherwise, after deleting the edge we add a directional edge from $y$ to $v$ and from $v$ to $x$. After these changes, for every $v$, $d^+(v) - d^-(v)$ will not change. However if there is no such vertex, the graph contains some paths and cycles in which the weight of each path and cycle is 1 or 2 every other one. So we can direct edges of each cycle to produce a directed cycle and do the same thing for edges of each path in order to make a directed path. By doing this, every $v$ with odd $c_v$ will become Oddysey.
[ "constructive algorithms", "dfs and similar", "graphs" ]
3,000
#include <bits/stdc++.h> #pragma GCC optimize ("O2,unroll-loops") using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define all(x) x.begin(), x.end() #define pb push_back #define SZ(x) ((int)x.size()) #define kill(x) return cout<<x<<'\n', 0; const int inf=1000000010; const ll INF=100000000000000100LL; const int mod=1000000007; const int MAXN=300010, LOG=19; int n, m, mm, k, u, v, x, y, t, a, b; int U[MAXN], V[MAXN], W[MAXN], ans[MAXN]; int deg[MAXN], parr[MAXN][3], mark[MAXN]; vector<int> G[MAXN][3], E[MAXN]; vector<pii> G2[MAXN]; inline void orient(int i, int u){ if (u==U[i]){ ans[i]=1; deg[U[i]]-=W[i]; deg[V[i]]+=W[i]; } else{ ans[i]=2; deg[U[i]]+=W[i]; deg[V[i]]-=W[i]; } } void MergePath(int i, int w){ mm++; int v=i; while (1){ while (SZ(G[v][w]) && mark[G[v][w].back()]) G[v][w].pop_back(); if (G[v][w].empty()) break ; int i=G[v][w].back(); assert(!mark[i]); mark[i]=1; E[mm].pb(i); int u=(U[i]^V[i]^v); parr[u][w]^=1; parr[v][w]^=1; v=u; } if (E[mm].empty()){ mm--; return ; } G2[i].pb({v, mm}); G2[v].pb({i, -mm}); } void dfs(int v){ while (SZ(G2[v]) && mark[abs(G2[v].back().second)]) G2[v].pop_back(); if (G2[v].empty()) return ; int u=G2[v].back().first, id=G2[v].back().second; if (id<0){ id*=-1; reverse(all(E[id])); } mark[id]=1; for (int i:E[id]){ orient(i, v); v^=V[i]^U[i]; } assert(v==u); dfs(u); } int main(){ ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n>>m; for (int i=0; i<m; i++){ cin>>U[i]>>V[i]>>W[i]; parr[U[i]][W[i]]^=1; parr[V[i]][W[i]]^=1; G[U[i]][W[i]].pb(i); G[V[i]][W[i]].pb(i); } int sum=0; for (int i=1; i<=n; i++) sum+=parr[i][1]; for (int i=1; i<=n; i++) for (int w:{1, 2}) if (parr[i][w]) MergePath(i, w); for (int i=1; i<=n; i++) for (int w:{1, 2}) MergePath(i, w); for (int i=0; i<m; i++){ assert(mark[i]); mark[i]=0; } for (int i=1; i<=n; i++) if (SZ(G2[i])&1) dfs(i); for (int i=1; i<=n; i++) dfs(i); cout<<sum<<"\n"; for (int i=0; i<m; i++) cout<<ans[i]; cout<<"\n"; return 0; }
1610
G
AmShZ Wins a Bet
Right before the UEFA Euro 2020, AmShZ and Safar placed bets on who'd be the champion, AmShZ betting on Italy, and Safar betting on France. Of course, AmShZ won. Hence, Safar gave him a bracket sequence $S$. Note that a bracket sequence is a string made of '(' and ')' characters. AmShZ can perform the following operation any number of times: - First, he cuts his string $S$ into three (possibly empty) contiguous substrings $A, B$ and $C$. Then, he glues them back by using a '(' and a ')' characters, resulting in a new string $S$ = $A$ + "(" + $B$ + ")" + $C$.For example, if $S$ = "))((" and AmShZ cuts it into $A$ = "", $B$ = "))", and $C$ = "((", He will obtain $S$ = "()))((" as a new string. After performing some (possibly none) operations, AmShZ gives his string to Keshi and asks him to find the initial string. Of course, Keshi might be able to come up with more than one possible initial string. Keshi is interested in finding the lexicographically smallest possible initial string. Your task is to help Keshi in achieving his goal. 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$.
Idea: AmShZ, Keshi, Preparation: AmShZ, Keshi, alireza_kaviani, AliShahali1382 We can prove that there exists a way to achieve the lexicographically minimum by removing some balanced substrings. (A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters "+" and "1".) We will remove some pairs of indices. If there is a pair that we don't remove all the characters between them, by using that character instead of one the initial ones the answer either stays the same or becomes lexicographically smaller. Because if the character in between is "(", changing the pair is like moving a "(" closer to the front of the outcome which will make it smaller. And if it's ")", changing the pair is like moving a ")" farther from the front of the outcome which will make it smaller. For each $i$ find the shortest non-empty balanced substring that starts in index $i$. Let the length of this substring be $l$. Set $nxt_i$ as $i + l$, or $i$ if no such substring exists. For each $i$ we either keep the $i$-th character or remove every character in $[i, nxt_i)$ interval. Imagine we somehow store the answer for each suffix. Then $ans_i = \min(s_i + ans_{i + 1}, ans_{nxt_i})$. $\textbf{Read the Hints and Assumptions before reading this.}$
[ "data structures", "greedy", "hashing" ]
3,300
//In the name of God #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; const ll maxn = 3e5 + 100; const ll lg = 20; const ll mod = 1e9 + 7; const ll inf = 1e18; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define file_io freopen("input.txt", "r+", stdin);freopen("output.txt", "w+", stdout); #define pb push_back #define Mp make_pair #define F first #define S second #define Sz(x) ll((x).size()) #define all(x) (x).begin(), (x).end() ll n, par[maxn][lg], h[maxn][lg], ls[maxn + maxn], ps[maxn], nxt[maxn], a[maxn], d[maxn], p[maxn]; string s; ll check(ll v, ll u){ for(ll i = lg; i--;){ if(d[v] < (1 << i) || d[u] < (1 << i)) continue; if(h[v][i] == h[u][i]){ v = par[v][i]; u = par[u][i]; } } if(d[v] == 0) return 1; return (h[v][0] < h[u][0]); } int main(){ fast_io; p[0] = 1; for(ll i = 1; i < maxn; i++){ p[i] = p[i - 1] * 2 % mod; } cin >> s; n = Sz(s); s = ' ' + s; for(ll i = 1; i <= n; i++){ ps[i] = ps[i - 1] + (s[i] == '(' ? 1 : -1); } for(ll i = n + 1; i > 0; i--){ nxt[i] = i; if(s[i] == '(' && ls[ps[i - 1] + maxn]){ nxt[i] = ls[ps[i - 1] + maxn]; } ls[ps[i - 1] + maxn] = i; } a[n + 1] = n + 1; for(ll i = n; i > 0; i--){ par[i][0] = a[i + 1]; h[i][0] = (s[i] == '(' ? 0 : 1); d[i] = d[par[i][0]] + 1; for(ll j = 1; j < lg; j++){ if(d[i] < (1 << j)) break; par[i][j] = par[par[i][j - 1]][j - 1]; h[i][j] = (h[i][j - 1] * p[(1 << (j - 1))] + h[par[i][j - 1]][j - 1]) % mod; } a[i] = i; if(check(a[nxt[i]], i)){ a[i] = a[nxt[i]]; } } ll v = a[1]; while(v != n + 1){ cout << (h[v][0] ? ')' : '('); v = par[v][0]; } cout << "\n"; return 0; }
1610
H
Squid Game
After watching the new \sout{over-rated} series Squid Game, Mashtali and Soroush decided to hold their own Squid Games! Soroush agreed to be the host and will provide money for the winner's prize, and Mashtali became the Front Man! $m$ players registered to play in the games to win the great prize, but when Mashtali found out how huge the winner's prize is going to be, he decided to \sout{kill} eliminate all the players so he could take the money for himself! Here is how evil Mashtali is going to eliminate players: There is an unrooted tree with $n$ vertices. Every player has $2$ special vertices $x_i$ and $y_i$. In one operation, Mashtali can choose any vertex $v$ of the tree. Then, for each remaining player $i$ he finds a vertex $w$ on the simple path from $x_i$ to $y_i$, which is the closest to $v$. If $w\ne x_i$ and $w\ne y_i$, player $i$ will be eliminated. Now Mashtali wondered: "What is the minimum number of operations I should perform so that I can remove every player from the game and take the money for myself?" Since he was only thinking about the money, he couldn't solve the problem by himself and asked for your help!
A player gets eliminated iff $(x_i, y_i)$ is a cross-edge while rooting the tree from where Mashtali sits. we say a vertex is marked if Mashtali choses it in a move. Lets solve the problem in polynomial time. First, lets fix one of the marked vertices and root the tree from it. Then all cross-edges are already covered and we have a set of back-edges to cover. Then, we can use this greedy approach: At each step, take the lowest uncovered back-edge and mark the second highest vertex in its path.(the highest one is either $x_i$ or $y_i$ which is not allowed) You can prove its correct using the fact that there is no lower back-edges, so if we mark a higher vertex all vertices that were marked before, are marked now. So far the complexity is smth like $O(n^3)$. But we can use fenwick-tree to check whether an edge is covered or not. Which leads to a $O(n^2 \cdot log(n))$ solution. Now, let's forget about fixing one of the moves! let's just make the tree rooted at $1$, ignore all cross-edges, and do the previous solution. Finally, check if there is an uncovered cross-edge. If so, just put a token on $1$. Now, why is that correct? if all cross-edges are covered, everything is ok. So we just need to show we need more marked vertices if a cross-edge is uncovered. If that happens, it means all our tokens are either in subtree of $x_i$ or in subtree of $y_i$. Since we put our tokens at highest possible nodes, there is no vertex that would mark the cross-edge and a back-edge with it. So, we need to mark at least one more vertex and the root, suffice. time complexity: $O(n \cdot log(n))$
[ "data structures", "dfs and similar", "greedy", "trees" ]
3,100
#include <bits/stdc++.h> #pragma GCC optimize ("O2,unroll-loops") using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<pii, int> piii; typedef pair<ll, ll> pll; #define debug(x) cerr<<#x<<'='<<(x)<<endl; #define debugp(x) cerr<<#x<<"= {"<<(x.first)<<", "<<(x.second)<<"}"<<endl; #define debug2(x, y) cerr<<"{"<<#x<<", "<<#y<<"} = {"<<(x)<<", "<<(y)<<"}"<<endl; #define debugv(v) {cerr<<#v<<" : ";for (auto x:v) cerr<<x<<' ';cerr<<endl;} #define all(x) x.begin(), x.end() #define pb push_back #define SZ(x) ((int)x.size()) #define kill(x) return cout<<x<<'\n', 0; const int inf=1000000010; const ll INF=100000000000000100LL; const int mod=1000000007; const int MAXN=300010, LOG=19; int n, m, k, u, v, x, y, t, a, b, ans; int par[LOG][MAXN], h[MAXN], P[MAXN]; int stt[MAXN], fnt[MAXN], timer=1; int fen[MAXN]; vector<int> G[MAXN], vec[MAXN], out; int GetPar(int v, int k){ for (int i=0; k; i++) if (k&(1<<i)){ k^=(1<<i); v=par[i][v]; } return v; } inline void add(int pos, int val){ for (; pos<MAXN; pos+=pos&-pos) fen[pos]+=val; } inline int get(int pos){ int res=0; for (; pos; pos-=pos&-pos) res+=fen[pos]; return res; } inline int get2(int v){ return get(fnt[v]-1)-get(stt[v]-1);} void dfs(int node){ stt[node]=timer++; for (int v:G[node]) dfs(v); fnt[node]=timer; } int main(){ ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n>>m; for (int i=2; i<=n; i++){ cin>>par[0][i]; G[par[0][i]].pb(i); h[i]=h[par[0][i]]+1; for (int j=1; j<LOG; j++) par[j][i]=par[j-1][par[j-1][i]]; } dfs(1); while (m--){ cin>>x>>y; if (h[x]>h[y]) swap(x, y); if (par[0][y]==x) kill(-1) vec[x].pb(y); } iota(P+1, P+n+1, 1); sort(P+1, P+n+1, [](int i, int j){ return h[i]>h[j];}); vector<pii> crossE; for (int i=1; i<=n; i++){ int x=P[i]; for (int y:vec[x]){ if (h[x]==h[y]){ crossE.pb({x, y}); continue ; } int yy=GetPar(y, h[y]-h[x]-1); if (par[0][yy]!=x){ crossE.pb({x, y}); continue ; } if (get2(yy)-get2(y)) continue ; ans++; out.pb(yy); add(stt[yy], +1); } } for (pii p:crossE){ int x=p.first, y=p.second; if (get2(x)+get2(y)<ans) continue ; out.pb(1); ans++; break ; } cout<<ans<<"\n"; return 0; }
1611
A
Make Even
Polycarp has an integer $n$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: - Reverse the prefix of length $l$ (in other words, $l$ leftmost digits) of $n$. So, the leftmost digit is swapped with the $l$-th digit from the left, the second digit from the left swapped with ($l-1$)-th left, etc. For example, if $n=123456789$ and $l=5$, then the new value of $n$ will be $543216789$. Note that for different operations, the values of $l$ can be different. The number $l$ can be equal to the length of the number $n$ — in this case, the whole number $n$ is reversed. Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible. Help Polycarp. Determine the minimum number of operations he needs to perform with the number $n$ to make it even or determine that this is impossible. You need to answer $t$ independent test cases.
If the number is already even, then nothing needs to be done, so the answer in this case is 0. Now let's recall the divisibility by $2$: a number is divisible by $2$ if and only if its last digit is divisible by $2$. It follows that if there are no even digits in our number, then the answer is -1. Let's take a look at our operation. What is going on? The first digit always changes with the digit numbered $l$. In particular, when we reverse the entire number, the first digit is swapped with the last. Note that no other digit, except for the first one at the current moment, can't be the last. Therefore, you can do this: if the first digit of a number is divisible by $2$, then we reverse the whole number. The first digit will become the last, and the number will become even. Therefore, you only need to do one operation. Now, what if the first digit of a number is odd? In this case, we can find the first even digit in the number (let it be at position $x$), and reverse the prefix of length $x$ (in one operation). Now the first digit of our number has become even, and we can use the previous case (one more operation). Thus, we will do only 2 operations.
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { string n; cin >> n; if((n.back() - '0') % 2 == 0) { cout << "0\n"; continue; } if((n[0] - '0') % 2 == 0) { cout << "1\n"; continue; } int count_2 = count(n.begin(), n.end(), '2'); int count_4 = count(n.begin(), n.end(), '4'); int count_6 = count(n.begin(), n.end(), '6'); int count_8 = count(n.begin(), n.end(), '8'); if(count_2 > 0 || count_4 > 0 || count_6 > 0 || count_8 > 0) { cout << "2\n"; continue; } cout << "-1\n"; } return 0; }
1611
B
Team Composition: Programmers and Mathematicians
The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate. There are $a$ programmers and $b$ mathematicians at Berland State University. How many maximum teams can be made if: - each team must consist of exactly $4$ students, - teams of $4$ mathematicians or $4$ programmers are unlikely to perform well, so the decision was made not to compose such teams. Thus, each team must have at least one programmer \textbf{and} at least one mathematician. Print the required maximum number of teams. Each person can be a member of no more than one team.
If necessary, change the values of $a$ and $b$ so that $a \le b$ is always true. Consider two cases. 1. Let $a \le \frac{a + b}{4}$. Then: $4a \le a + b$, $3a \le b$. This means that the set $b$ is at least $3$ times larger than $a$, and we can form $a$ teams of the form $(1, 3)$, where one participant will be a programmer and three will be mathematicians. 2. Let $\frac{a + b}{4} \le a$. Then assume that $b = a + d$. Let's substitute this value into the inequality: $\frac{2a + d}{4} \le a$, $2a + d \le 4a$ $d \le 2a$, $\frac{d}{2} \le a$ Then we compose $\frac{d}{2}$ commands of the form $(1, 3)$. Since making such a command decreases the value of $d$ by 2. The new value $a' = a - \frac{d}{2}$, $b' = a' + d - 2 * (\frac{d}{2})$. The condition $a' \le b'$ still holds. Then make $\frac{a'}{2}$ commands of the form $(2, 2)$. The total number of commands is $\frac{a'}{2} + \frac{d}{2} = \frac{2*a' + 2*d}{4} = \frac{2*a - d + 2*d}{4} = \frac{a + (a+d)}{4} = \frac{a+b}{4}$. That's what we wanted to get.
[ "binary search", "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { ll a, b; cin >> a >> b; cout << min(min(a, b), (a + b) / 4) << '\n'; } int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { solve(); } return 0; }
1611
C
Polycarp Recovers the Permutation
Polycarp wrote on a whiteboard an array $p$ of length $n$, which is a permutation of numbers from $1$ to $n$. In other words, in $p$ each number from $1$ to $n$ occurs exactly once. He also prepared a resulting array $a$, which is initially empty (that is, it has a length of $0$). After that, he did exactly $n$ steps. Each step looked like this: - Look at the leftmost and rightmost elements of $p$, and pick the smaller of the two. - If you picked the leftmost element of $p$, append it to the left of $a$; otherwise, if you picked the rightmost element of $p$, append it to the right of $a$. - The picked element is erased from $p$. Note that on the last step, $p$ has a length of $1$ and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to $a$ both on the left and on the right (at the discretion of Polycarp). Let's look at an example. Let $n=4$, $p=[3, 1, 4, 2]$. Initially $a=[]$. Then: - During the first step, the minimum is on the right (with a value of $2$), so after this step, $p=[3,1,4]$ and $a=[2]$ (he added the value $2$ to the right). - During the second step, the minimum is on the left (with a value of $3$), so after this step, $p=[1,4]$ and $a=[3,2]$ (he added the value $3$ to the left). - During the third step, the minimum is on the left (with a value of $1$), so after this step, $p=[4]$ and $a=[1,3,2]$ (he added the value $1$ to the left). - During the fourth step, the minimum is both left and right (this value is $4$). Let's say Polycarp chose the right option. After this step, $p=[]$ and $a=[1,3,2,4]$ (he added the value $4$ to the right). Thus, a possible value of $a$ after $n$ steps could be $a=[1,3,2,4]$. You are given the final value of the resulting array $a$. Find \textbf{any} possible initial value for $p$ that can result the given $a$, or determine that there is no solution.
The maximum element is always added last, so if it is not in the first or last position, then there is no answer. Let us prove that if the permutation has its maximum element in the first or last position, then after $n$ actions we can get an expanded permutation. Indeed, the maximum element will be added last at the desired end, and all the others will be added in reverse order. Then, if the answer exists, it is sufficient to simply unfold the permutation.
[ "constructive algorithms" ]
1,000
#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<int> a(n); forn(i, n) cin >> a[i]; if (a[0] != n && a[n - 1] != n) cout << -1 << endl; else { for (int i = n - 1; i >= 0; i--) cout << a[i] << " "; cout << endl; } } }
1611
D
Weights Assignment For Tree Edges
You are given a rooted tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. Any vertex can be the root of a tree. A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The tree is specified by an array of ancestors $b$ containing $n$ numbers: $b_i$ is an ancestor of the vertex with the number $i$. The ancestor of a vertex $u$ is a vertex that is the next vertex on a simple path from $u$ to the root. For example, on the simple path from $5$ to $3$ (the root), the next vertex would be $1$, so the ancestor of $5$ is $1$. The root has no ancestor, so for it, the value of $b_i$ is $i$ (the root is the only vertex for which $b_i=i$). For example, if $n=5$ and $b=[3, 1, 3, 3, 1]$, then the tree looks like this. \begin{center} {\small An example of a rooted tree for $n=5$, the root of the tree is a vertex number $3$.} \end{center} You are given an array $p$ — a permutation of the vertices of the tree. If it is possible, assign any \textbf{positive} integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $p$. In other words, for a given permutation of vertices $p$, it is necessary to choose such edge weights so that the condition $dist[p_i]<dist[p_{i+1}]$ is true for each $i$ from $1$ to $n-1$. $dist[u]$ is a sum of the weights of the edges on the path from the root to $u$. In particular, $dist[u]=0$ if the vertex $u$ is the root of the tree. For example, assume that $p=[3, 1, 2, 5, 4]$. In this case, the following edge weights satisfy this permutation: - the edge ($3, 4$) has a weight of $102$; - the edge ($3, 1$) has weight of $1$; - the edge ($1, 2$) has a weight of $10$; - the edge ($1, 5$) has a weight of $100$. The array of distances from the root looks like: $dist=[1,11,0,102,101]$. The vertices sorted by increasing the distance from the root form the given permutation $p$. Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.
Consider the cases when it is impossible to form a given permutation $p$: 1. The first vertex in the permutation is not the root of the tree. For root $u$ it is true that $dist[u]=0$. For any other vertex $i$ the value of $dist[i]$ will be positive, since there is at least one edge of positive weight on the path to it. 2. The distance to the child is less than to the parent. In a rooted tree there is exactly one path from the root to any vertex $i$, and it goes through its parent $b_i$, so it must always be true $dist[b[i]] < dist[i]$. Let us start filling the array $dist$, where $dist[p[1]] = 0$. Consider a vertex $p[i]$, ($2 \le p[i] \le n$). The vertex whose distance at the current time is maximal is $p[i - 1]$. Then $dist[p[i]]$ is at least $dist[p[i - 1]] + 1$. We assign a value to $dist[i]$, remembering to check that $dist[b[i]]$ has already been counted. After counting all $dist[i]$ values, we can output the lengths of the edges: $w[i] = dist[i] - dist[b[i]]$.
[ "constructive algorithms", "trees" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int> b(n + 1), p(n + 1), dist(n + 1, -1); for(int i = 1; i <= n; i++) cin >> b[i]; for(int i = 1; i <= n; i++) cin >> p[i]; if (b[p[1]] != p[1]){ cout << -1 << '\n'; return; } dist[p[1]] = 0; for(int i = 2; i <= n; i++){ if(dist[b[p[i]]] == -1){ cout << -1 << '\n'; return; } dist[p[i]] = dist[p[i - 1]] + 1; } for(int i = 1; i <= n; i++) { cout << dist[i] - dist[b[i]] << ' '; } cout << '\n'; } int main() { int t; cin >> t; while(t-- > 0) { solve(); } }
1611
E1
Escape The Maze (easy version)
The only difference with E2 is the question of the problem.. Vlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree. Vlad invited $k$ friends to play a game with them. Vlad starts the game in the room $1$ and wins if he reaches a room other than $1$, into which exactly one corridor leads. Friends are placed in the maze: the friend with number $i$ is in the room $x_i$, and no two friends are in the same room (that is, $x_i \neq x_j$ for all $i \neq j$). Friends win if one of them meets Vlad in any room or corridor before he wins. For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play). In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.
First, we need to understand when it is not possible to get to some exit $e$. Let's fix a friend who is at the vertex $f$ and try to understand if he can interfere with us. The paths from $1$ to $e$ and from $f$ to $e$ have a common part, let it start at the vertex $v$. Then, if the path from $f$ to $v$ is not more than from $1$ to $v$, it can prevent us from reaching this exit by blocking the vertex $v$. Since the path from $v$ to $e$ is common, the previous condition is equivalent to the condition that the path from $f$ to $e$ is not greater than from $1$ to $e$. Note that if there is more than one such vertex $e$, then $f$ can overlap each of them, simply by going as close to the root as possible. Thus, Vlad can win if there is such a leaf (which, by condition, exits) for which the distance to the root is less than the distance to any of the friends. By running a breadth-first search at the same time from each vertex with a friend, we can find the shortest distance to any friend from each vertex and by running from the root - the distance to the root. Now let's just go through all the leaves and check if there is one among them that the distance to the root is less. We can also run from the vertices with friends and from the root at the same time, assigning them different colors, then the color will correspond to what is closer: the root or some friend. this solution is attached to the tutorial. There is also another solution, which is a simplified version of the one we will use in E2.
[ "dfs and similar", "greedy", "shortest paths", "trees", "two pointers" ]
1,700
// // Created by Vlad on 16.11.2021. // #include <bits/stdc++.h> #define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e10; const int M = 998244353; const ld pi = atan2(0, -1); const ld eps = 1e-4; void solve() { int n, k; cin >> n >> k; vector<int> color(n, -1); deque<int> q; for(int i = 0; i < k; ++i){ int x; cin >> x; color[--x] = 0; q.push_back(x); } color[0] = 1; q.push_back(0); vector<vector<int>> g(n); for(int i = 0; i < n - 1; ++i){ int u, v; cin >> u >> v; g[--u].push_back(--v); g[v].push_back(u); } while(!q.empty()){ int v = q.front(); q.pop_front(); for(int u: g[v]){ if(color[u] == -1){ color[u] = color[v]; q.push_back(u); } } } for(int v = 1; v < n; ++v){ if(g[v].size() == 1 && color[v] == 1){ cout << "YES"; return; } } cout << "NO"; } bool multi = true; signed main() { int t = 1; if (multi) { cin >> t; } for (; t != 0; --t) { solve(); cout << "\n"; } return 0; }
1611
E2
Escape The Maze (hard version)
The only difference with E1 is the question of the problem. Vlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree. Vlad invited $k$ friends to play a game with them. Vlad starts the game in the room $1$ and wins if he reaches a room other than $1$, into which exactly one corridor leads. Friends are placed in the maze: the friend with number $i$ is in the room $x_i$, and no two friends are in the same room (that is, $x_i \neq x_j$ for all $i \neq j$). Friends win if one of them meets Vlad in any room or corridor before he wins. For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what \textbf{minimum} number of friends must remain in the maze so that they can always catch Vlad. In other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.
Let's learn how to find an answer for the subtree rooted in vertex $v$. At first, it is obvious from E1 tutorial that if the nearest to $v$ vertex with a friend from this subtree is no further from it than the root of the entire tree from $v$, then the answer for the entire subtree is $1$ since a friend can come to $v$ and catch Vlad in it not allowing him to go to any leaf of this subtree. Else we will find the answer leaning on its children. If a solution does not exist for at least one child, then it does not exist for the entire subtree, because after reaching $v$ Vlad will be able to go to such child and reach any exit. Otherwise, the answer for $v$ is the sum of the answers of its children, since we need to beat it in each subtree to win, and for each subtree, we have found the minimum answer.
[ "dfs and similar", "dp", "greedy", "shortest paths", "trees" ]
1,900
#include <bits/stdc++.h> #define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() /*#pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native") #pragma GCC optimize("fast-math") */ typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e10; const int M = 998244353; const ld pi = atan2(0, -1); const ld eps = 1e-4; vector<vector<int>> sl; vector<int> nearest; int count(int v, int dist, int p = -1){ bool children = true; int s = 0; for(int u: sl[v]){ if(u == p) continue; int c = count(u, dist + 1, v); if(c < 0) children = false; nearest[v] = min(nearest[v], nearest[u] + 1); s += c; } if(nearest[v] <= dist) return 1; if(s == 0 || !children) return -1; return s; } void solve() { int n, k; cin >> n >> k; sl.assign(n, vector<int>(0)); nearest.assign(n, n); for(int i = 0; i < k; ++i){ int x; cin >> x; --x; nearest[x] = 0; } for(int i = 1; i < n; ++i){ int u, v; cin >> u >> v; --u, --v; sl[u].emplace_back(v); sl[v].emplace_back(u); } cout << count(0, 0); } bool multi = true; signed main() { //freopen("in.txt", "r", stdin); //freopen("in.txt", "w", stdout); /*ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);*/ int t = 1; if (multi) { cin >> t; } for (; t != 0; --t) { solve(); cout << "\n"; } return 0; }
1611
F
ATM and Students
Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains $s$ rubles. A queue of $n$ students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If $a_i$ is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws $|a_i|$ rubles. In the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of $s$ rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore. More formally, the students that are served are forming a \textbf{contiguous subsequence}. Polycarp wants the ATM to serve the \textbf{maximum} number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone. In other words, find such a longest continuous segment of students that, starting with the sum of $s$ at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).
At first glance, this is a standard problem for ST (Segment Tree). Let's solve the problem in that way. First, we find the prefix sums of the $a$ array and store them in $p$. Let's build an ST on the prefix array and store the min in it. For each index $l$ $(1 \le l \le n)$, we'll make a query in ST and will find such a minimum index $r$ ($l \le r$) that the sum on the subsegment $[l, r]$ of the array $a$ and $s$ will be negative, in other words $s + (p [r] -p [l-1]) \lt 0$ or $s - p [l-1] \lt -p [r]$, the sum of s is obtained and the subsegment $[l, r)$ of the array $a$ will be non-negative, in other words, $s + (p [r-1] - p [l-1]) \ge 0$. Accordingly, the correct response to the request will be $l$ and $r-1$. Of all such pairs of indices $l$ and $r-1$, we take such that the distance between them is maximal. If for all pairs $l == r$, then the answer is $-1$. The hardest part here is the querys. Actually, here's a query that returns $r-1$ for index $l$ or $-1$ if $l == r$: Btw, after each request for $l$ do not forget to change in ST the element that corresponds to $p[l]$ to MAX_INT, so that it does not interfere with us. Time complexity is $O(n \cdot log(n))$.
[ "binary search", "data structures", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) vector<ll> t, a; ll s, tl; const ll MAX = 1'000'000'000'000'000LL; void build(int v, int l, int r) { if (l == r) t[v] = a[l]; else { int m = (l + r) / 2; build (v * 2, l, m); build (v * 2 + 1, m + 1, r); t[v] = min(t[v * 2], t[v * 2 + 1]); } } void update(int v, int l, int r) { if (l == r) t[v] = MAX; else { int m = (l + r) / 2; if (tl <= m) update(v * 2, l, m); else update(v * 2 + 1, m + 1, r); t[v] = min(t[v * 2], t[v * 2 + 1]); } } int lower_bound_s(int v, int l, int r) { if (r < tl || (l == r && s < -t[v])) { return -1; } if (l == r || -t[v] <= s) { return r; } int m = (l + r) / 2; if (m < tl) { return lower_bound_s(2 * v + 1, m + 1, r); } if (s < -t[2 * v]) { return lower_bound_s(2 * v, l, m); } int res = lower_bound_s(2 * v + 1, m + 1, r); return (res == -1) ? m : res; } int main() { int tests; cin >> tests; forn(tt, tests) { int n; cin >> n >> s; t = vector<ll>(4 * n); a = vector<ll>(n); forn(i, n) { cin >> a[i]; } for (int i = 1; i < n; ++i) { a[i] += a[i - 1]; } build(1, 0, n - 1); int first = -1, second = -2; for (tl = 0; tl < n; ++tl) { int v = lower_bound_s(1, 0, n - 1); if (v != -1 && v - tl > second - first) { first = tl + 1; second = v + 1; } s -= a[tl]; if (tl != 0) s += a[tl - 1]; update(1, 0, n - 1); } if (first == -1) { cout << -1; } else { cout << first << " " << second; } cout << endl; } }
1611
G
Robot and Candies
Polycarp has a rectangular field of $n \times m$ cells (the size of the $n \cdot m$ field does not exceed $10^6$ cells, $m \ge 2$), in each cell of which there can be candy. There are $n$ rows and $m$ columns in the field. Let's denote a cell with coordinates $x$ vertically and $y$ horizontally by $(x, y)$. Then the top-left cell will be denoted as $(1, 1)$, and the bottom-right cell will be denoted as $(n, m)$. If there is candy in the cell, then the cell is marked with the symbol '1', otherwise — with the symbol '0'. Polycarp made a Robot that can collect candy. The Robot can move from $(x, y)$ either to $(x+1, y+1)$, or to $(x+1, y-1)$. If the Robot is in a cell that contains candy, it takes it. While there is at least one candy on the field, the following procedure is executed: - Polycarp puts the Robot in an arbitrary cell on the \textbf{topmost row} of the field. He himself chooses in which cell to place the Robot. It is allowed to put the Robot in the same cell multiple times. - The Robot moves across the field and collects candies. He controls the Robot. - When the Robot leaves the field, Polycarp takes it. If there are still candies left, Polycarp repeats the procedure. Find the \textbf{minimum} number of times Polycarp needs to put the Robot on the topmost row of the field in order to collect all the candies. It is guaranteed that Polycarp can always collect all the candies.
Note first that we can solve the two subtasks independently if we consider the coloring as on a chessboard, since at any move of the robot the parity of $x + y$ does not change. Now replace the moves $(x+1, y-1)$, $(x+1, y+1)$ with moves $(x+1, y)$, $(x+1, y+1)$ respectively. This can be done because we simply shifted the rows by some value, with the Robot walking on the same cells it walked on in the original board. Let's look at the even numbered (gray) cells: Changed field Then we'll go through the columns from left to right, keeping the minimum(by size) set of cells the Robot should be in. Then the transition to the next column will be as follows. Go through the cells from bottom to top, which contain the candy. For each cell, find the closest cell of our set (find the Robot) that is above the current cell. Then we change the square from the set to the current square. If there is no robot for the square in the array, then we need to increase the answer by $1$ and add the robot to our current square (you can think of it as adding the robot to the very top square in the column and getting all the candies that were above). In the picture, the red circles indicate the cells where we will put the robot as needed. The pink cells mean that this cell is contained in the set. The final asymptotic depends on the implementation (you can use a set as data structure, or you can use a vector with two pointers): $O(n*m*log(n))$ and $O(n*m)$, respectively.
[ "data structures", "graph matchings", "greedy" ]
2,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() const int N = 1e6 + 50; string a[N]; int n,m; int ans; void solve(int sum0) { vector<int> v; for (int sum = sum0, ad = 0, pref = 0; sum < n + m; sum += 2, ad++) { vector<int> cur; int li = max(0, sum - m + 1), ri = min(n - 1, sum); if (li > ri) continue; for (int i = li; i <= ri; i++) { int j = sum - i; if (a[i][j] == '1') cur.emplace_back(i); } while (pref != sz(v) && v[pref] + ad > ri) { pref++; } for (int i = pref; i < sz(v); i++) { int new_val = v[i]; while (!cur.empty() && cur.back() - ad >= v[i]) { new_val = max(new_val, cur.back() - ad); cur.pop_back(); } v[i] = new_val; } if (!cur.empty()) { v.emplace_back(cur.back() - ad); ans++; } } } int main() { int t; cin >> t; forn(tt, t) { cin >> n >> m; forn(i, n) { string s; cin >> a[i]; } ans = 0; solve(0); solve(1); cout << ans << '\n'; } }
1612
A
Distance
Let's denote the Manhattan distance between two points $p_1$ (with coordinates $(x_1, y_1)$) and $p_2$ (with coordinates $(x_2, y_2)$) as $d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$. For example, the distance between two points with coordinates $(1, 3)$ and $(4, 2)$ is $|1 - 4| + |3 - 2| = 4$. You are given two points, $A$ and $B$. The point $A$ has coordinates $(0, 0)$, the point $B$ has coordinates $(x, y)$. Your goal is to find a point $C$ such that: - both coordinates of $C$ are non-negative integers; - $d(A, C) = \dfrac{d(A, B)}{2}$ (without any rounding); - $d(B, C) = \dfrac{d(A, B)}{2}$ (without any rounding). Find any point $C$ that meets these constraints, or report that no such point exists.
There is a solution in $O(1)$, but in fact, a solution that checks all points with $x$-coordinate from $0$ to $50$ and $y$-coordinate from $0$ to $50$ is fast enough. There's no need to check any other points, since $d(A, C) + d(B, C) = d(A, B)$ implies that point $C$ is on one of the shortest paths between $A$ and $B$.
[ "brute force", "constructive algorithms" ]
800
t = int(input()) for i in range(t): x, y = map(int, input().split()) xc = -1 yc = -1 for j in range(0, 51): for k in range(0, 51): if 2 * (j + k) == x + y and 2 * (abs(x - j) + abs(y - k)) == x + y: xc, yc = j, k print(xc, yc)
1612
B
Special Permutation
A permutation of length $n$ is an array $p=[p_1,p_2,\dots, p_n]$ which contains every integer from $1$ to $n$ (inclusive) exactly once. For example, $p=[4, 2, 6, 5, 3, 1]$ is a permutation of length $6$. You are given three integers $n$, $a$ and $b$, where $n$ is an even number. Print any permutation of length $n$ that the minimum among \textbf{all its elements of the left half} equals $a$ and the maximum among \textbf{all its elements of the right half} equals $b$. Print -1 if no such permutation exists.
There are many different constructions that give the correct answer, if it exists. In my opinion, one of the most elegant is the following one. $a$ should always be present in the left half, and $b$ should be present in the right half, but the exact order of elements in each half doesn't matter. So, it will never be wrong to put $a$ in the first position, and $b$ in the second position. As for the remaining elements, we want elements of the left half to be as big as possible (since they shouldn't be less than $a$), and elements of the right half - as small as possible (since they shouldn't be greater than $b$). Let's put the elements $n$, $n - 1$, $n - 2$, ..., $1$ (excluding $a$ and $b$) on positions $2$, $3$, $4$, ..., $n-1$, respectively, so the elements in the left half are as big as possible, and the elements in the right half are as small as possible. After constructing a permutation according to these rules, we should check if it meets the constraints (and print it if it does).
[ "constructive algorithms", "greedy" ]
900
t = int(input()) for i in range(t): n, a, b = map(int, input().split()) p = [a] for j in range(n, 0, -1): if j != a and j != b: p.append(j) p.append(b) if(len(p) == n and min(p[0:n//2]) == a and max(p[n//2:n]) == b): print(*p) else: print(-1)
1612
C
Chat Ban
You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something. More precisely, you want to spam the emote triangle of size $k$. It consists of $2k-1$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $k$-th one — of $k$ emotes, the $k+1$-th one — of $k-1$ emotes, ..., and the last one — of one emote. For example, the emote triangle for $k=3$ consists of $5$ messages: Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $x$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $2k-1$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted. You have to answer $t$ independent test cases.
This is a pretty obvious binary search problem. If we get banned after $y$ messages, we also get banned after $y+1$, $y+2$ and so on messages (and vice versa, if we don't get banned after $y$ messages, we also don't get banned after $y-1$, $y-2$ and so on messages). For simplicity, let's split the problem into two parts: when we check if we're getting banned after $y$ messages, let's handle cases $y < k$ and $y \ge k$ separately. Recall that the sum of the arithmetic progression consisting of integers $1$, $2$, ..., $y$ is $\frac{y(y+1)}{2}$. Let it be $cnt(y)$. The first case is pretty simple: the number of emotes we send with $y$ messages when $y < k$ is $\frac{y(y+1)}{2}$ which is $cnt(y)$. So we only need to check if $cnt(y) \ge x$. The second case is a bit harder but still can be done using arithmetic progression formulas. Firstly, we send all messages for $y \le k$ (the number of such messages is $cnt(k)$). Then, we need to add $(k - 1) + (k - 2) + \ldots + (y - k)$ messages. This number equals to $cnt(k - 1) - cnt(2k - 1 - y)$ (i.e. we send all messages from $k-1$ to $1$ and subtract messages from $1$ to $2k - 1 - y$ from this amount). The final condition is $cnt(k) + cnt(k - 1) - cnt(2k - 1 - y) \ge x$. Time complexity: $O(\log{k})$ per test case.
[ "binary search", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; long long get(int x) { return x * 1ll * (x + 1) / 2; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int k; long long x; cin >> k >> x; long long l = 1, r = 2 * k - 1; long long res = 2 * k - 1; bool over = false; while (l <= r) { int mid = (l + r) >> 1; if (mid >= k) { over = (get(k) + get(k - 1) - get(2 * k - 1 - mid) >= x); } else { over = (get(mid) >= x); } if (over) { res = mid; r = mid - 1; } else { l = mid + 1; } } cout << res << endl; } return 0; }
1612
D
X-Magic Pair
You are given a pair of integers $(a, b)$ and an integer $x$. You can change the pair in two different ways: - set (assign) $a := |a - b|$; - set (assign) $b := |a - b|$, where $|a - b|$ is the absolute difference between $a$ and $b$.The pair $(a, b)$ is called $x$-magic if $x$ is obtainable either as $a$ or as $b$ using only the given operations (i.e. the pair $(a, b)$ is $x$-magic if $a = x$ or $b = x$ after some number of operations applied). You can apply the operations any number of times (even zero). Your task is to find out if the pair $(a, b)$ is $x$-magic or not. You have to answer $t$ independent test cases.
This problem has a GCD-based solution. Firstly, lets' try to solve it naively. Always suppose that $a > b$. If this is not true, let's swap $a$ and $b$. Firstly, if $b > a - b$, let's do $b := a - b$. Okay, now let's subtract $b$ from $a$ until $b \ge a - b$ again and repeat this algorithm till $a = 0$ or $b = 0$. If, after some step, we get $a = x$ or $b = x$, we are done, and the answer is YES. If $a = 0$ or $b = 0$, and we didn't get $x$ then the answer is NO. Okay, we can see that we always subtract the minimum possible $b$ from $a$ and trying to maintain this condition. It can be proven that this algorithm yields all possible integers that are obtainable by any sequence of the operations from the problem statement (either in $a$ or in $b$). Now we have to speed up this solution somehow. Obviously, most operations are redundant for us in this particular problem. The first thing is that we can skip all operations till $b$ becomes greater than $a - b$. The number of such operations is $\lfloor\frac{a - b}{2b}\rfloor$. And the second thing is that we can skip all operations till we get $x$ in $a$. The number of such operations is $\lfloor\frac{a-x}{b}\rfloor$. For simplicity, this part can be also written as $\lfloor\frac{a-x}{2b}\rfloor$. This doesn't affect the time complexity much, but the formula for the final number of operations we can skip will be simpler. This number equals $cnt = max(1, \lfloor\frac{a-max(b, x)}{2b}\rfloor)$ (in fact, we take the minimum between two values written above, because we don't want to skip any of these two cases). So, we can transform the pair $(a, b)$ to the pair $(a - b * cnt, b)$ and continue this algorithm. There are also simpler approaches using the same idea but in a cooler way. Time complexity: $O(\log{a})$ per test case.
[ "math", "number theory" ]
1,600
#include <bits/stdc++.h> using namespace std; bool get(long long a, long long b, long long x) { if (a == x || b == x) return true; if (a < b) swap(a, b); if (b > a - b) b = a - b; if (x > max(a, b) || a == 0 || b == 0) return false; long long cnt = max(1ll, (a - max(x, b)) / (2 * b)); return get(a - b * cnt, b, x); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { long long a, b, x; cin >> a >> b >> x; if (get(a, b, x)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0; }
1612
E
Messages
Monocarp is a tutor of a group of $n$ students. He communicates with them using a conference in a popular messenger. Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student $i$ to read the message $m_i$. Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise \textbf{it will definitely be skipped by everyone}. Unfortunately, even if a message is pinned, some students may skip it anyway. For each student $i$, Monocarp knows that they will read at most $k_i$ messages. Suppose Monocarp pins $t$ messages; if $t \le k_i$, then the $i$-th student will read all the pinned messages; but if $t > k_i$, the $i$-th student will choose exactly $k_i$ random pinned messages (all possible subsets of pinned messages of size $k_i$ are equiprobable) and read only the chosen messages. Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices $i$ that student $i$ reads the message $m_i$). Help him to choose how many (and which) messages should he pin!
First of all, let's rewrite the answer using expectation linearity. The expected number of students who read their respective messages is equal to $F_1 + F_2 + \dots + F_n$, where $F_i$ is a random value which is $1$ if the $i$-th student reads the message $m_i$, and $0$ if the $i$-th student doesn't do it. Let's analyze the expected value of $F_i$. Suppose Monocarp pins the messages $c_1, c_2, \dots, c_t$. There are three cases: if $m_i \notin [c_1, c_2, \dots, c_t]$, then the $i$-th student won't read the message $m_i$, so $F_i = 0$; if $m_i \in [c_1, c_2, \dots, c_t]$ and $t \le k_i$, then the $i$-th student will definitely read the message $m_i$, so $F_i = 1$; if $m_i \in [c_1, c_2, \dots, c_t]$ and $t > k_i$, then $F_i = \frac{k_i}{t}$. If we iterate on the number of messages we pin $t$, we can calculate the sum of $F_i$ for each message (considering that we pin it), sort all of the messages and pick $t$ best of them. So, we have a solution working in $O(n^2 \log n)$. The only thing we need to improve this solution sufficiently is the fact that we don't have to consider the case $t > 20$. Since every $k_i$ is not greater than $20$, the sum of $F_i$ for a message in the case $t = 20$ is the same as this sum of $F_i$ in the case $t = 21$, but multiplied by the coefficient $\frac{20}{21}$ - and we pick $21$ best values, their sum multiplied by $\frac{20}{21}$ is not greater than the sum of $20$ best values. The same holds for $t = 22$ and greater.
[ "brute force", "dp", "greedy", "probabilities", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 200043; const int K = 20; vector<int> idx[N]; int m[N], k[N]; bool frac_greater(pair<int, int> a, pair<int, int> b) { return a.first * b.second > a.second * b.first; } int main() { int n; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d %d", &m[i], &k[i]); idx[m[i]].push_back(i); } vector<int> cert; pair<int, int> ans = {0, 1}; for(int i = 1; i <= K; i++) { vector<int> score(N); for(int j = 0; j < n; j++) score[m[j]] += min(i, k[j]); vector<pair<int, int>> aux; for(int j = 0; j < N; j++) aux.push_back(make_pair(score[j], j)); sort(aux.rbegin(), aux.rend()); pair<int, int> cur_ans = {0, i}; vector<int> cur_cert; for(int j = 0; j < i; j++) { cur_ans.first += aux[j].first; cur_cert.push_back(aux[j].second); } if(frac_greater(cur_ans, ans)) { ans = cur_ans; cert = cur_cert; } } cout << cert.size() << endl; shuffle(cert.begin(), cert.end(), mt19937(time(NULL))); for(auto x : cert) cout << x << " "; cout << endl; }
1612
F
Armor and Weapons
Monocarp plays a computer game. There are $n$ different sets of armor and $m$ different weapons in this game. If a character equips the $i$-th set of armor and wields the $j$-th weapon, their power is usually equal to $i + j$; but some combinations of armor and weapons synergize well. Formally, there is a list of $q$ ordered pairs, and if the pair $(i, j)$ belongs to this list, the power of the character equipped with the $i$-th set of armor and wielding the $j$-th weapon is not $i + j$, but $i + j + 1$. Initially, Monocarp's character has got only the $1$-st armor set and the $1$-st weapon. Monocarp can obtain a new weapon or a new set of armor in one hour. If he wants to obtain the $k$-th armor set or the $k$-th weapon, he must possess a combination of an armor set and a weapon that gets his power to $k$ \textbf{or greater}. Of course, after Monocarp obtains a weapon or an armor set, he can use it to obtain new armor sets or weapons, but he can go with any of the older armor sets and/or weapons as well. Monocarp wants to obtain the $n$-th armor set \textbf{and} the $m$-th weapon. What is the minimum number of hours he has to spend on it?
Among two armor sets, one with the greater index is always better. The same can be said about two different weapons. So, it is always optimal to use and obtain the best possible weapon or armor. This observation allows us to model this problem with dynamic programming or shortest paths: let $dp_{x,y}$ be the minimum time in which Monocarp can obtain the armor $x$ and the weapon $y$; and in each transition, we either get the best weapon we can or the best armor we can. Similarly, we can build a graph where the vertices represent these pairs $(x, y)$, and the edges represent getting the best possible weapon/armor, and find the shortest path from $(1, 1)$ to $(n, m)$ using BFS. Unfortunately, it is $O(nm)$. But we can modify the BFS in the following fashion: let's analyze each layer of BFS (a layer is a set of vertices with the same distance from the origin). In each layer, there might be some redundant vertices: if two vertices $(x, y)$ and $(x', y')$ belong to the same layer, $x' \le x$ and $y' \le y$, then the vertex $(x', y')$ is redundant. If we filter each layer, removing all redundant vertices from it and continuing BFS only from non-redundant ones, the solution will be fast enough. To prove it, let's analyze the constraints on the answer. Suppose $n \ge m$. The answer can be bounded as $O(\log m + \frac{n}{m})$, since we can reach the pair $(m, m)$ in $O(\log m)$ steps using something similar to Fibonacci sequence building, and then go from $(m, m)$ to $(n, m)$ in $\frac{n}{m}$ steps. And the number of non-redundant states on each layer is not greater than $m$ (because, of two states with the same weapon or the same armor set, at least one is redundant). So, if we don't continue BFS from redundant vertices, it will visit at most $O(m \cdot (\log m + \frac{n}{m})) = O(m \log m + n)$ vertices. There might be another logarithm in the asymptotic complexity of the solution, if you use something like a set to store all combinations that synergize well, but this implementation is still fast enough.
[ "brute force", "dp", "greedy", "shortest paths" ]
2,800
#include<bits/stdc++.h> using namespace std; int n, m; #define x first #define y second typedef pair<int, int> comb; comb norm(const comb& a) { return make_pair(min(a.x, n), min(a.y, m)); } bool good(const comb& a) { return a.x == n || a.y == m; } bool comp(const comb& a, const comb& b) { if(a.x != b.x) return a.x > b.x; return a.y > b.y; } int main() { scanf("%d %d", &n, &m); int v; scanf("%d", &v); set<comb> s; for(int i = 0; i < v; i++) { int x, y; scanf("%d %d", &x, &y); s.insert(make_pair(x, y)); } int steps = 0; vector<comb> cur; cur.push_back(make_pair(1, 1)); while(true) { if(cur[0] == make_pair(n, m)) break; vector<comb> ncur; for(auto x : cur) { int sum = x.x + x.y; if(s.count(x)) sum++; comb z = x; z.x = sum; ncur.push_back(norm(z)); z = x; z.y = sum; ncur.push_back(norm(z)); } sort(ncur.begin(), ncur.end(), comp); int mx = 0; vector<comb> ncur2; for(auto x : ncur) { if(x.y <= mx) continue; mx = max(mx, x.y); ncur2.push_back(x); } cur = ncur2; steps++; } printf("%d\n", steps); }
1612
G
Max Sum Array
You are given an array $c = [c_1, c_2, \dots, c_m]$. An array $a = [a_1, a_2, \dots, a_n]$ is constructed in such a way that it consists of integers $1, 2, \dots, m$, and for each $i \in [1,m]$, there are exactly $c_i$ occurrences of integer $i$ in $a$. So, the number of elements in $a$ is exactly $\sum\limits_{i=1}^{m} c_i$. Let's define for such array $a$ the value $f(a)$ as $$f(a) = \sum_{\substack{1 \le i < j \le n\\ a_i = a_j}}{j - i}.$$ In other words, $f(a)$ is the total sum of distances between all pairs of equal elements. Your task is to calculate the maximum possible value of $f(a)$ and the number of arrays yielding the maximum possible value of $f(a)$. Two arrays are considered different, if elements at some position differ.
Firstly, let's prove that at first and last positions of $a$ the most frequent elements should be placed (but not necessary the same). WLOG, let's prove that $c_{a_1} \ge c_{a_i}$ for any $i > 1$. By contradiction, let's $p$ be the smallest index such that $c_{a_1} < c_{a_p}$. What happens if we swap them? Since $p$ is the first such index then there are no $a_i = a_p$ for $i < p$, so "contribution" of $a_p$ will increase by exactly $inc = (c_{a_p} - 1) \cdot (p - 1)$. From the other side, contribution of $a_1$ consists of two parts: pairs with elements from $(p, n]$ and from $(1, p)$. For all elements from $(p, n]$ decrease will be equal to $dec_1 = c_{a_1}[p + 1, n] \cdot (p - 1)$ and from elements in $(1, p)$ $dec_2 \le c_{a_1}[2, p - 1] \cdot (p - 1)$. So, the total decrease $dec$ after moving $a_1$ to position $p$ equal to $dec = dec_1 + dec_2 \le (c_{a_1} - 1) \cdot (p - 1)$. The total difference in such case is equal to $inc - dec \ge (p - 1) \cdot (c_{a_p} - c_{a_1}) > 0$. So, our placement is not optimal - contradiction. Let's suggest that there is exactly one $e$ with maximum $c_{e}$. According to what we proved earlier, both $a_1$ and $a_n$ must be equal to $e$. Contribution of the first and last elements will be equal to: $(n - 1)$ for pair $(1, n)$ and for each element $i$ ($1 < i < n$) with $a_i = e$ we add $(i - 1) + (n - i) = (n - 1)$ for pairs $(1, i)$ and $(i, n)$. So, the total contribution of $a_1 = a_n = e$ is equal to $(n - 1) \cdot (c_e - 1)$. Note that this contribution is independent of positions of other $e$ in the array $a$, so that's why we can cut first and last elements of $a$ and solve the task recursively. Unfortunately, in the initial task we may have several $e_1, e_2, \dots, e_k$ with maximum $c_{e_i}$. But we in the similar manner can prove that the first (and last) $k$ elements $a_1, \dots, a_k$ should be some permutation of $e_1, \dots e_k$. Now, let's prove that any permutation of first and last $k$ elements is optimal. Suppose, positions of $e_i$ are $l_i$ ($1 \le l_i \le k$) and $r_i$ ($n - k + 1 \le r_i \le n$). Then the contribution of $e_i$ is equal to $(c_{e_i} - 1) \cdot (r_i - l_i)$. The total contribution of all $e_i$ is $\sum\limits_{i=1}^{k}{(c_{e_i} - 1) \cdot (r_i - l_i)}$ $=$ $(c_{e_1} - 1) (\sum\limits_{i=1}^{k}r_i - \sum\limits_{i=1}^{k}{l_i})$ $=$ $(c_{e_1} - 1)((n - k)k + \frac{k(k + 1)}{2} - \frac{k(k+1)}{2}) = (c_{e_1} - 1) k (n - k)$. This contribution doesn't depend on chosen $l_i$ and $r_i$, so any permutation of first $k$ elements and any permutation of last $k$ elements give optimal answer. As a result, the algorithm is following: Find all maximums $e_1, \dots, e_k$ in $c$. If $c_{e_1} = 1$ then any permutation of remaining elements has $f(a) = 0$ (there are $k!$ such permutations). Otherwise, add $(c_{e_1} - 1) k (n - k)$ to the total balance, and multiply the number of variants by $(k!)^2$. Cut prefix and suffix by making $c_{e_i} = c_{e_i} - 2$ for each $e_i$ (obviously, $n = n - 2k$) and repeat the whole process. We can implement the algorithm fast if we keep the number of $c_i$ equal to each $val$ from $0$ to $C$ ($C \le 10^6$). So the total complexity is $O(n + C)$.
[ "combinatorics", "constructive algorithms", "greedy", "sortings" ]
2,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << " " << p.y << ")"; } template<class A> ostream& operator <<(ostream& out, const vector<A> &v) { fore(i, 0, sz(v)) { if(i) out << " "; out << v[i]; } return out; } const int INF = int(1e9); const li INF64 = li(1e18); const int MOD = int(1e9) + 7; int norm(int a) { while (a >= MOD) a -= MOD; while (a < 0) a += MOD; return a; } int mul(int a, int b) { return int(a * 1ll * b % MOD); } const int MX = int(1e6) + 55; int n; li total; int cnt[MX]; inline bool read() { if(!(cin >> n)) return false; total = 0; fore (i, 0, n) { int k; cin >> k; cnt[k]++; total += k; } return true; } int fact[MX]; inline void solve() { fact[0] = 1; fore (i, 1, MX) fact[i] = mul(fact[i - 1], i); int ansSum = 0; int ansCnt = 1; for (int lvl = MX - 1; lvl > 1; lvl--) { ansCnt = mul(ansCnt, mul(fact[cnt[lvl]], fact[cnt[lvl]])); //each color gives (lvl - 1) * (r_i - l_i) // or (lvl - 1) * (sum r_i - sum l_i) // l_i is permutation of [0,..., cnt[lvl]), so sum l_i = (cnt[lvl] - 1) * cnt[lvl] / 2 // r_i is permutation of [total - cnt[lvl],..., total), so sum = cnt[lvl] * (total - cnt[lvl]) + (cnt[lvl] - 1) * cnt[lvl] / 2 ansSum = norm(ansSum + mul(mul(lvl - 1, cnt[lvl]), (total - cnt[lvl]) % MOD)); total -= 2 * cnt[lvl]; cnt[lvl - 2] += cnt[lvl]; } ansCnt = mul(ansCnt, fact[cnt[1]]); cout << ansSum << " " << ansCnt << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1613
A
Long Comparison
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $x$ with $p$ zeros appended to its end. Now Monocarp asks you to compare these two numbers. Can you help him?
First, let's say that appending the number with $p$ zeros is the same as multiplying it by $10^p$. The given numbers are so large that they can't fit into any reasonable integer type. Even if you use a language with unlimited length integers (python, for example) or store the numbers in strings, you should still face the time limit issue. So let's learn to shrink the numbers a bit. Note that the result of the comparison of two numbers doesn't change if you divide both numbers by the same positive number. So we can keep dividing both numbers by $10$ until one of them is not divisible anymore. Let's also ignore the trailing zeros in $x_1$ and $x_2$ and leave them as is. If the first number is appended with $p_1$ zeros and the second numbers is appended with $p_2$ zeros, we can subtract $min(p_1, p_2)$ from both values, effectively dividing both numbers by $10^{min(p_1, p_2)}$. This way, one of the numbers becomes short enough to fit into an integer type (because it has $p=0$ and $x$ is only up to $10^6$). The other number might still be large enough. However, if it's really large, we can instantly say that it's larger than another one. Say, if its $p$ is at least $7$. This number it at least $10^7$ and the other number is at most $10^6$. Otherwise, we can calculate this number as well and compare the values normally. Overall complexity: $O(1)$ per testcase.
[ "implementation", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ long long x1, x2; int p1, p2; cin >> x1 >> p1 >> x2 >> p2; int mn = min(p1, p2); p1 -= mn; p2 -= mn; if (p1 >= 7) cout << ">" << endl; else if (p2 >= 7) cout << "<" << endl; else{ for (int i = 0; i < p1; ++i) x1 *= 10; for (int i = 0; i < p2; ++i) x2 *= 10; if (x1 < x2) cout << "<" << endl; else if (x1 > x2) cout << ">" << endl; else cout << "=" << endl; } } }
1613
B
Absent Remainder
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ pairwise distinct positive integers. Find $\left\lfloor \frac n 2 \right\rfloor$ different pairs of integers $x$ and $y$ such that: - $x \neq y$; - $x$ and $y$ appear in $a$; - $x~mod~y$ doesn't appear in $a$. Note that some $x$ or $y$ can belong to multiple pairs. $\lfloor x \rfloor$ denotes the floor function — the largest integer less than or equal to $x$. $x~mod~y$ denotes the remainder from dividing $x$ by $y$. If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.
There is one important observation: $x~mod~y<y$. Thus, you can obtain at least $n-1$ pair by choosing $y$ as the minimum number in the sequence and $x$ as anything else. $n-1 \ge \left\lfloor \frac n 2 \right\rfloor$ for any positive $n$. Overall complexity: $O(n)$ per testcase.
[ "greedy", "implementation", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; int mn = *min_element(a.begin(), a.end()); for (int i = 0, k = 0; k < n / 2; ++i) if (a[i] != mn) { cout << a[i] << ' ' << mn << '\n'; k += 1; } } }
1613
C
Poisoned Dagger
Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $100^{500}$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $i$-th attack is performed at the beginning of the $a_i$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $1$ damage during each of the next $k$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one). For example, suppose $k = 4$, and Monocarp stabs the dragon during the seconds $2$, $4$ and $10$. Then the poison effect is applied at the start of the $2$-nd second and deals $1$ damage during the $2$-nd and $3$-rd seconds; then, at the beginning of the $4$-th second, the poison effect is reapplied, so it deals exactly $1$ damage during the seconds $4$, $5$, $6$ and $7$; then, during the $10$-th second, the poison effect is applied again, and it deals $1$ damage during the seconds $10$, $11$, $12$ and $13$. In total, the dragon receives $10$ damage. Monocarp knows that the dragon has $h$ hit points, and if he deals at least $h$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $k$ (the number of seconds the poison effect lasts) that is enough to deal at least $h$ damage to the dragon.
Let's find out the total damage for a fixed value of $k$. Since the effect of the poison from the $i$-th attack deals damage $\min(k, a_{i+1} - a_i)$ seconds for $i < n$ and $k$ seconds for $i = n$, then the total damage is $k +\sum\limits_{i=1}^{n-1}{\min(k, a_{i+1} - a_i)}$. We can see that the higher the value of $k$, the greater the total sum. So we can do a binary search on $k$ and find the minimum value when the sum is greater than or equal to $h$.
[ "binary search" ]
1,200
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { int t; cin >> t; while (t--) { int n; li h; cin >> n >> h; vector<li> a(n); for (li &x : a) cin >> x; li l = 1, r = 1e18; while (l <= r) { li m = (l + r) / 2; li sum = m; for (int i = 0; i < n - 1; ++i) sum += min(m, a[i + 1] - a[i]); if (sum < h) l = m + 1; else r = m - 1; } cout << r + 1 << '\n'; } }
1613
D
MEX Sequences
Let's call a sequence of integers $x_1, x_2, \dots, x_k$ MEX-correct if for all $i$ ($1 \le i \le k$) $|x_i - \operatorname{MEX}(x_1, x_2, \dots, x_i)| \le 1$ holds. Where $\operatorname{MEX}(x_1, \dots, x_k)$ is the minimum non-negative integer that doesn't belong to the set $x_1, \dots, x_k$. For example, $\operatorname{MEX}(1, 0, 1, 3) = 2$ and $\operatorname{MEX}(2, 1, 5) = 0$. You are given an array $a$ consisting of $n$ non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo $998244353$. Note: a subsequence of an array $a$ is a sequence $[a_{i_1}, a_{i_2}, \dots, a_{i_m}]$ meeting the constraints $1 \le i_1 < i_2 < \dots < i_m \le n$. If two different ways to choose the sequence of indices $[i_1, i_2, \dots, i_m]$ yield the same subsequence, the resulting subsequence should be counted twice (i. e. two subsequences are different if their sequences of indices $[i_1, i_2, \dots, i_m]$ are not the same).
Let's understand what MEX-correct sequences look like. It turns out there are only two types: $[\underline{0, \dots, 0}, \underline{1, \dots, 1}, \dots, \underline{x-1, \dots, x-1}, \underline{x, \dots, x}]$ and $[\underline{0, \dots, 0}, \underline{1, \dots, 1}, \dots, \underline{x-1, \dots, x-1}, \underline{x+1, \dots, x+1}, \underline{x-1, \dots, x-1}, \underline{x+1, \dots}]$. For example, the sequences $[0, 0, 1, 1, 1, 2, 3, 3]$ and the empty sequence are MEX-correct sequences of the first type, and $[1, 1, 1, 1]$ and $[0, 0, 1, 2, 4, 4, 2, 4, 2, 2]$ of the second one. Let's calculate the dynamic programming $\mathrm{dp1}_{i, j}$ - the number of MEX-correct subsequences of the first type on the prefix of length $i$ with $\operatorname{MEX}$ equal to $j$ and similarly $\mathrm{dp2}_{i, j}$ - the number of MEX-correct subsequences of the second type on the prefix of length $i$ with $\operatorname{MEX}$ equal to $j$. Let's look at the transitions in these dps, and show that there are no other MEX-correct sequences at the same time. Let the current state be $\mathrm{dp1}_{i, j}$, and we are trying to add an element equal to $x$: if $x < j - 1$, then such an element cannot be added; if $x = j - 1$, then the value of $\operatorname{MEX}$ will not change and the sequence is still of the first type, which means we have a transition to $\mathrm{dp1}_{i + 1, j}$; if $x = j$, then the value of $\operatorname{MEX}$ will increase by $1$, but it will still be of the first type, which means we have a transition to $\mathrm{dp1}_{i + 1, j + 1}$ if $x = j + 1$, then the value of $\operatorname{MEX}$ will not change, but the sequence will become of the second type, which means we have a transition to $\mathrm{dp2}_{i + 1, j}$; if $x > j + 1$, then such an element cannot be added. Let the current state be $\mathrm{dp2}_{i, j}$, and we are trying to add an element equal to $x$: if $x < j - 1$, then such an element cannot be added; if $x = j - 1$, then the value of $\operatorname{MEX}$ will not change and the sequence is still of the second type, which means we have a transition to $\mathrm{dp2}_{i + 1, j}$; if $x = j$, then such an element cannot be added, because $\operatorname{MEX}$ will increase by $2$, which means the absolute difference between $\operatorname{MEX}$ and $x$ is greater than $1$; if $x = j + 1$, then the value of $\operatorname{MEX}$ will not change and the sequence is still of the second type, which means we have a transition to $\mathrm{dp2}_{i + 1, j}$; if $x > j + 1$, then such an element cannot be added. Thus, we considered all possible transitions (adding a new element to the already MEX-correct sequences) and made sure that there are only two types. While the solution itself works in $O(n)$ time (because each element $x$ has $O(1)$ possible transitions in the dps), it uses $O(n^2)$ memory, which does not allow us to write that solution as is. However, note that $\mathrm{dp1}_i$ and $\mathrm{dp1}_{i + 1}$ (similarly for $\mathrm{dp2}$) differ in only a few positions (in those that the element $a_i$ allowed us to make), which means we can store only one-dimensional arrays, $\mathrm{dp1}_j$ and $\mathrm{dp2}_j$. Thus, the final complexity of the solution is $O(n)$.
[ "dp", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; return x; } int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); vector<int> dp1(n + 2), dp2(n + 2); dp1[0] = 1; while (n--) { int x; scanf("%d", &x); dp1[x + 1] = add(dp1[x + 1], dp1[x + 1]); dp1[x + 1] = add(dp1[x + 1], dp1[x]); if (x > 0) dp2[x - 1] = add(dp2[x - 1], dp2[x - 1]); if (x > 0) dp2[x - 1] = add(dp2[x - 1], dp1[x - 1]); dp2[x + 1] = add(dp2[x + 1], dp2[x + 1]); } int ans = 0; for (int x : dp1) ans = add(ans, x); for (int x : dp2) ans = add(ans, x); printf("%d\n", add(ans, MOD - 1)); } }
1613
E
Crazy Robot
There is a grid, consisting of $n$ rows and $m$ columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked. A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: "move right", "move down", "move left" or "move up". Each command means moving to a neighbouring cell in the corresponding direction. However, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing. We want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.
One way to think about this problem is in game theory terms. Imagine a following game. Two players alternate moves. The first players chooses a direction. The second player chooses a different direction and moves a robot there. The game ends when the robot reaches the lab, and the first player wins. Otherwise, it's a draw. What's the outcome of the game if both players play optimally (as in the first player tries to win, the second player tries to draw)? Does it sound easier? Well, it sure does if you ever dealt with solving games on arbitrary graphs. You can skim through this article if that's unfamiliar to you. The state of the game is a pair $(\mathit{cell}, \mathit{direction})$. If a direction is not chosen (denote it with $-1$), it's the first player's move. Otherwise, it's the second player's move. You can even implement it as is. Or you can adjust a part of this algorithm for this particular problem. Initially, all the states are drawing, only the state $(\mathit{lab}, -1)$ is winning. What we basically need is a way to determine if a state is winning or not. From game theory, we can tell that the state is winning if there's a transition from it to a losing state. The state is losing if all the transitions from it lead to winning states. So $(\mathit{cell}, -1)$ is winning if any of $(\mathit{cell}, \mathit{direction} \neq -1)$ are losing. Promote that one step further. The state is winning if there exists such a direction that all neighbouring free cells except in this direction are winning states. Rephrase it. The state is winning if it has at least one winning state neighbour and no more than one non-winning state neighbour. Let's store the number of non-winning neighbouring states for each cell. Initially, it's the number of neighbouring free cells. If some state becomes marked as winning, decrease the value for each of its neighbours by $1$. If some state's value reaches $0$ or $1$ after this operation, mark it as winning. Since what this does is basically a traversal of a grid, this can be done with a DFS/BFS, starting from the lab. Overall complexity: $O(nm)$ per testcase.
[ "dfs and similar", "graphs" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct cell{ int x, y; }; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { int t; cin >> t; while (t--){ int n, m; cin >> n >> m; vector<string> s(n); int lx = -1, ly = -1; forn(i, n){ cin >> s[i]; forn(j, m) if (s[i][j] == 'L'){ lx = i; ly = j; } } auto in = [&](int x, int y){ return 0 <= x && x < n && 0 <= y && y < m; }; vector<vector<int>> d(n, vector<int>(m, 0)); forn(x, n) forn(y, m) if (s[x][y] == '.'){ forn(i, 4){ int nx = x + dx[i]; int ny = y + dy[i]; d[x][y] += in(nx, ny) && s[nx][ny] != '#'; } } queue<cell> q; vector<vector<char>> used(n, vector<char>(m, 0)); q.push({lx, ly}); used[lx][ly] = true; while (!q.empty()){ int x = q.front().x; int y = q.front().y; q.pop(); forn(i, 4){ int nx = x + dx[i]; int ny = y + dy[i]; if (!in(nx, ny) || s[nx][ny] == '#' || used[nx][ny]) continue; --d[nx][ny]; if (d[nx][ny] <= 1){ used[nx][ny] = true; q.push({nx, ny}); } } } forn(i, n){ forn(j, m) if (s[i][j] == '.' && used[i][j]) s[i][j] = '+'; cout << s[i] << "\n"; } } return 0; }
1613
F
Tree Coloring
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is the vertex $1$. You have to color all vertices of the tree into $n$ colors (also numbered from $1$ to $n$) so that there is exactly one vertex for each color. Let $c_i$ be the color of vertex $i$, and $p_i$ be the parent of vertex $i$ in the rooted tree. The coloring is considered beautiful if there is no vertex $k$ ($k > 1$) such that $c_k = c_{p_k} - 1$, i. e. no vertex such that its color is less than the color of its parent by \textbf{exactly $1$}. Calculate the number of beautiful colorings, and print it modulo $998244353$.
When a problem asks us to calculate the number of combinatorial objects that meet some constraints, we can sometimes use inclusion-exclusion formula. Let's try to apply it in this problem. We could use $n-1$ constraints that should not be violated. The $i$-th constraint is formulated as follows: $c_i \ne c_{p_i} - 1$ (there will be a constraint of this type for each $i \in [2, n]$). Suppose we violated $k$ of these constraints (and have chosen which $k$ constraints to violate), then the number of colorings that meet these violations is $(n-k)!$ (for $k$ vertices, the colors on them depend on some other independent vertices, so we can assign only colors for independent vertices). So, the answer can be calculated as follows: $\sum\limits_{k=0}^{n-1} (-1)^k f(k) (n-k)!$ where $f(k)$ is the number of ways to choose $k$ constraints to violate. One initial guess how to calculate $f(k)$ is that $f(k) = {{n-1}\choose{k}}$, as it would be calculated in other, more usual inclusion-exclusion problems. Unfortunately, in this problem, the constraints we violate are not independent. For example, if a vertex has several sons, we can violate the constraint only on at most one edge leading from a vertex to its son simultaneously, we cannot violate two or more such constraints. Let's take care of this issue as follows: we can write a dynamic programming of the form $dp_{i, j}$ is the number of ways to process $i$ first vertices of the tree and choose exactly $j$ edges leading from these nodes to their sons so that no vertex has more than one edge leading to its sons chosen. Then, $dp_{n, k}$ is exactly the number of ways to choose $k$ edges in the tree so that no vertex has more than one chosen edge leading to its sons, and that will be equal to $f(k)$. We can calculate this dynamic programming in a knapsack fashion in $O(n^2)$, but it is too slow. Instead, let's optimize this knapsack DP with FFT: for each vertex $i$, introduce a polynomial $1 + d_i \cdot x$, where $d_i$ is the number of children of the vertex $i$. Coefficients of this polynomial for the first vertex are the values of $dp_{1,k}$; coefficients of the product of this polynomial with the polynomial for the second vertex are the values of $dp_{2,k}$, and so on; to obtain the values of $dp_{n,k}$, we have to multiply all these polynomials, and using FFT + divide-and-conquer, we can do it in $O(n \log^2 n)$.
[ "combinatorics", "divide and conquer", "fft" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int(r); ++i) #define sz(a) int((a).size()) const int MOD = 998244353; struct Mint { int val; bool operator==(const Mint& other) { return val == other.val; } Mint operator+(const Mint& other) { int res = val + other.val; while(res >= MOD) res -= MOD; while(res < 0) res += MOD; return Mint(res); } Mint operator-(const Mint& other) { int res = val - other.val; while(res >= MOD) res -= MOD; while(res < 0) res += MOD; return Mint(res); } Mint operator*(const Mint& other) { return Mint((val * 1ll * other.val) % MOD); } Mint pow(int y) { Mint z(1); Mint x(val); while(y > 0) { if(y % 2 == 1) z = z * x; x = x * x; y /= 2; } return z; } Mint operator/(const Mint& other) { return Mint(val) * Mint(other.val).pow(MOD - 2); } Mint() { val = 0; }; Mint(int x) { while(x >= MOD) x -= MOD; while(x < 0) x += MOD; val = x; }; }; ostream& operator<<(ostream& out, const Mint& x) { return out << x.val; } const int g = 3; const int LOGN = 19; vector<Mint> w[LOGN]; vector<int> rv[LOGN]; void prepare() { Mint wb = Mint(g).pow((MOD - 1) / (1 << LOGN)); forn(st, LOGN - 1) { w[st].assign(1 << st, 1); Mint bw = wb.pow(1 << (LOGN - st - 1)); Mint cw = 1; forn(k, 1 << st) { w[st][k] = cw; cw = cw * bw; } } forn(st, LOGN) { rv[st].assign(1 << st, 0); if (st == 0) { rv[st][0] = 0; continue; } int h = (1 << (st - 1)); forn(k, 1 << st) rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h); } } void ntt(vector<Mint> &a, bool inv) { int n = sz(a); int ln = __builtin_ctz(n); forn(i, n) { int ni = rv[ln][i]; if (i < ni) swap(a[i], a[ni]); } forn(st, ln) { int len = 1 << st; for (int k = 0; k < n; k += (len << 1)) { fore(pos, k, k + len){ Mint l = a[pos]; Mint r = a[pos + len] * w[st][pos - k]; a[pos] = l + r; a[pos + len] = l - r; } } } if (inv) { Mint rn = Mint(n).pow(MOD - 2); forn(i, n) a[i] = a[i] * rn; reverse(a.begin() + 1, a.end()); } } vector<Mint> mul(vector<Mint> a, vector<Mint> b) { int cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1)); a.resize(cnt); b.resize(cnt); ntt(a, false); ntt(b, false); vector<Mint> c(cnt); forn(i, cnt) c[i] = a[i] * b[i]; ntt(c, true); return c; } vector<Mint> norm(vector<Mint> a) { while(a.size() > 1 && a.back() == Mint(0)) a.pop_back(); return a; } const int N = 250043; vector<int> G[N]; int d[N]; Mint fact[N * 2]; Mint rev[N * 2]; void dfs(int x, int p) { if(p != x) d[p]++; for(auto y : G[x]) if(y != p) dfs(y, x); } Mint C(int n, int k) { return fact[n] * rev[k] * rev[n - k]; } int main() { prepare(); fact[0] = Mint(1); for(int i = 1; i < N * 2; i++) fact[i] = fact[i - 1] * i; for(int i = 0; i < N * 2; i++) rev[i] = Mint(1) / fact[i]; int n; scanf("%d", &n); for(int i = 0; i < n - 1; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; G[x].push_back(y); G[y].push_back(x); } dfs(0, 0); vector<vector<Mint>> cur; for(int i = 0; i < n; i++) if(d[i] > 0) cur.push_back(vector<Mint>({Mint(1), Mint(d[i])})); while(cur.size() > 1) { vector<vector<Mint>> ncur; for(int i = 0; i + 1 < cur.size(); i += 2) ncur.push_back(norm(mul(cur[i], cur[i + 1]))); if(cur.size() % 2 == 1) ncur.push_back(cur.back()); cur = ncur; } Mint ans = 0; for(int i = 0; i < cur[0].size(); i++) { if(i % 2 == 0) ans = ans + cur[0][i] * fact[n - i]; else ans = ans - cur[0][i] * fact[n - i]; } cout << ans << endl; }
1614
A
Divan and a Store
Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well. The store he came to has $n$ different chocolate bars, and the price of the $i$-th chocolate bar is $a_i$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $r$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $l$ dollars. Divan will not buy too cheap or too expensive bars. Divan is not going to spend all his money on chocolate bars, so he will spend at most $k$ dollars on chocolates. Please determine the maximum number of chocolate bars Divan can buy.
To solve this problem, let's use the following greedy algorithm. Let's sort the prices of chocolate bars in increasing order, after which we will go from left to right and take chocolates that have a price not less than $l$, but not more than $r$ until we run out of money. The number of chocolate bars that we took will be the answer to the problem. The resulting asymptotics in time: $\mathcal{O}(n\log{}n)$.
[ "brute force", "constructive algorithms", "greedy" ]
800
null
1614
B
Divan and a New Project
The company "Divan's Sofas" is planning to build $n + 1$ different buildings on a coordinate line so that: - the coordinate of each building is an integer number; - no two buildings stand at the same point. Let $x_i$ be the coordinate of the $i$-th building. To get from the building $i$ to the building $j$, Divan spends $|x_i - x_j|$ minutes, where $|y|$ is the absolute value of $y$. All buildings that Divan is going to build can be numbered from $0$ to $n$. The businessman will live in the building $0$, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the $i$-th building $a_i$ times, each time spending $2 \cdot |x_0-x_i|$ minutes for walking. Divan asks you to choose the coordinates for all $n + 1$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.
Obviously, the more often we have to go to the $i$ building, the closer it should be to the main office. This implies a greedy algorithm. Let's put the main office at $0$ and sort the rest by $a_i$. Then we put the most visited building at a point with a coordinate of $1$, the second at $-1$, the third at $2$, etc. The resulting asymptotics in time is $\mathcal{O}(n\log{}n)$.
[ "constructive algorithms", "sortings" ]
1,000
null
1614
C
Divan and bitwise operations
Once Divan analyzed a sequence $a_1, a_2, \ldots, a_n$ consisting of $n$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $a$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $a$. A sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements. For example, $[1, \, 2, \, 3, \, 4]$, $[2, \, 4]$, and $[2]$ are subsequences of $[1, \, 2, \, 3, \, 4]$, but $[4, \, 3]$ and $[0]$ are not. Divan was very proud of his analysis, but now he lost the sequence $a$, and also the coziness value! However, Divan remembers the value of bitwise OR on $m$ contiguous subsegments of the sequence $a$. It turns out that each element of the original sequence is contained in \textbf{at least one} of these $m$ segments. Divan asks you to help find the coziness of the sequence $a$ using the information he remembers. If several coziness values are possible, print any. As the result can be very large, print the value modulo $10^9 + 7$.
Let's count for each bit how many times it will be included in the answer. Let us now consider the $i$-th bit. Note that if no number contains the included $i$-th bit, then such a bit will never be included in the answer. Otherwise, each of the subsequences contains $i$-th bit even or odd number of times. If a bit enters an even number of times, then we should not count such a subsequence, because the bitwise exclusive OR for this bit will be zero. If the bit enters an odd number of times, then we must count such a subsequence, because the bitwise exclusive OR for this bit will be equal to one. It is stated that the number of subsequences in which the $i$-th bit enters an odd number of times is equal to $2^{n - 1}$. Let's prove it. Divide the numbers into two sets $A$ and $B$. In the set $A$ there will be numbers whose $i$th bit is off, in the set $B$ there will be numbers whose $i$-th bit is on. Note that the numbers from the set $A$ do not affect the answer in any way, because $x\; XOR\; 0 = 1$. Thus, whichever subset of $A$ we take, the $i$-th bit will not change its parity. There will be $2^{|A|}$ in total of such subsets. Let $k = 1$ if $|B|$ is even, or $k = 0$ if $|B|$ is odd. In order for the $i$-th bit to enter the subsequence an odd number of times, you need to take an odd number of elements from the set $B$. This number is equal to $C_{|B|}^{1} \, + \, C_{|B|}^{3} \, + \dots \, + \, C_{|B|}^{|B| - k} = 2^{|B| - 1}$. Thus, the $i$-th bit is included in exactly $2^{|A|}\cdot 2^{|B|- 1}= 2^{n - 1}$ subsequences, which was required to be proved. Then the solution to this problem turns out to be very simple: let $x$ be equal to the bitwise OR of all elements of the sequence (or, the same thing, bitwise OR of all given segments), then the answer will be equal to $x\cdot 2^{n - 1}$ modulo $10^9 + 7$. The resulting asymptotics in time: $\mathcal{O}(n)$.
[ "bitmasks", "combinatorics", "constructive algorithms", "dp", "math" ]
1,500
null
1614
D1
Divan and Kostomuksha (easy version)
\textbf{This is the easy version of the problem. The only difference is maximum value of $a_i$.} Once in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i),$$ where $\operatorname{gcd}(x_1, x_2, \ldots, x_k)$ denotes the greatest common divisor of integers $x_1, x_2, \ldots, x_k$, and $\operatorname{gcd}(x) = x$ for any integer $x$. Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order. Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.
Let's solve the dynamic programming problem. Let $dp_i$ be the maximum answer for all arrays, the last element of which is divisible by $i$. Let's calculate the dynamics from $C$ to $1$, where $C$ is the maximum value of $a_i$. Initially, $dp_i = cnt_i \cdot i$, where $cnt_i$ is the amount of $a_i = i$. How do we recalculate our dynamic programming? $dp_i = max(dp_i, dp_j + i \cdot (cnt_i - cnt_j))$, for all $j$ such that $j$ $mod$ $i = 0$ (i.e. $j$ is divisible by $i$). In this dynamic, we iterate over the past change of our $gcd$ on the prefix, and greedily add all possible elements. The resulting asymptotics in time is $\mathcal{O}(C\log{}C)$.
[ "dp", "number theory" ]
2,100
null
1614
D2
Divan and Kostomuksha (hard version)
\textbf{This is the hard version of the problem. The only difference is maximum value of $a_i$.} Once in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i),$$ where $\operatorname{gcd}(x_1, x_2, \ldots, x_k)$ denotes the greatest common divisor of integers $x_1, x_2, \ldots, x_k$, and $\operatorname{gcd}(x) = x$ for any integer $x$. Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order. Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.
To solve $D2$, we can notice that to recalculate the dynamics, we can iterate over all such $j$ that differ from $i$ by multiplying exactly $1$ prime number. Also, to speed up the solution, we can use the linear sieve of Eratosthenes to find primes and factorization. The resulting asymptotics in time: $\mathcal{O}(C\log{}\log{}C)$.
[ "dp", "number theory" ]
2,300
null
1614
E
Divan and a Cottage
Divan's new cottage is finally complete! However, after a thorough inspection, it turned out that the workers had installed the insulation incorrectly, and now the temperature in the house directly depends on the temperature outside. More precisely, if the temperature in the house is $P$ in the morning, and the street temperature is $T$, then by the next morning the temperature in the house changes according to the following rule: - $P_{new} = P + 1$, if $P < T$, - $P_{new} = P - 1$, if $P > T$, - $P_{new} = P$, if $P = T$. Here $P_{new}$ is the temperature in the house next morning.Divan is a very busy businessman, so sometimes he is not at home for long periods and does not know what the temperature is there now, so he hired you to find it. You will work for $n$ days. In the beginning of the $i$-th day, the temperature outside $T_i$ is first given to you. After that, on the $i$-th day, you will receive $k_i$ queries. Each query asks the following: "if the temperature in the house was $x_i$ at the morning of the \textbf{first} day, what would be the temperature in the house next morning (after day $i$)?" Please answer all the businessman's queries.
Let $ans_{temp}$ the current answer for temperature $temp$. Before all days, $ans_{temp}$ is considered equal to $temp$. In order to respond to a request with a temperature of $x$, we will just need to output the value of $ans_x$. But how to maintain $ans$? With the help of an implicit tree of segments, at the vertices of which the minimum and maximum will be stored, as well as the variable $add$, which will contain the value that needs to be added to the current vertex (that is, such a variable that is needed to perform lazy operations on the segment tree). At the beginning of the next day you get the temperature $T$. Now we need to change the current answer for some $temp$. We need to find such $ans_{temp}$ that $ans_{temp} <T$ and add $+1$ to them, and then find such $ans_{temp}$ that $ans_{temp} > T$ and add $-1$ to them. All this is not difficult to do, just starting from the root of the segment tree and stopping at the moments when: the maximum of the current vertex is less than $T$ - here we add $+1$; the minimum of the current vertex is greater than $T$ - here we add $-1$; the minimum of the vertex is equal to the maximum of the vertex (and, therefore, the $T$ itself) - here we do not add anything. The resulting asymptotics in time: $\mathcal{O}(n\log{}T)$.
[ "binary search", "data structures" ]
2,600
null
1615
A
Closing The Gap
There are $n$ block towers in a row, where tower $i$ has a height of $a_i$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: - Choose two indices $i$ and $j$ ($1 \leq i, j \leq n$; $i \neq j$), and move a block from tower $i$ to tower $j$. This essentially decreases $a_i$ by $1$ and increases $a_j$ by $1$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $\max(a)-\min(a)$. What's the minimum possible ugliness you can achieve, after any number of days?
If $\max(a) - \min(a)$ is strictly greater than $1$, you can apply the operation on the max and the min respectively, which brings them both closer to each other. In other words, it either decreases $\max(a) - \min(a)$ or leaves it the same. This implies that the answer is always $\leq 1$. Now what remains is determining whether the answer is $0$ or $1$. The answer can only be $0$ if the sum of the array is divisible by $n$, as the sum of the array can't change after an operation, and if it's not divisible by $n$ you can't make every element equal. This means that the answer is $0$ if the sum is divisible by $n$, and $1$ otherwise.
[ "greedy", "math" ]
800
null
1615
B
And It's Non-Zero
You are given an array consisting of all integers from $[l, r]$ inclusive. For example, if $l = 2$ and $r = 5$, the array would be $[2, 3, 4, 5]$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero? A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.
Let's solve the complement problem: find the largest subsequence of the array such that their bitwise AND is non-zero. Let $x$ be the bitwise and of the optimal subsequence. Since $x \neq 0$, at least one bit must be set in $x$. Let's iterate over that bit, call it $b$, and in each iteration, calculate the largest subsequence whose bitwise and has that bit set. For the $b$-th bit to be set in the final answer, every element in the chosen subsequence must have that bit set. Since choosing every element with the $b$-th bit on is a valid subsequence, this implies that the answer for the $b$-th bit is the number of elements that have the $b$-th bit set. Thus, the answer to the final problem is $n - \max\limits_{1 \leq b \leq 30} cnt_{b}$, where $cnt_b$ is the number of elements who have the $b$-th bit set. Note: it doesn't matter if the final answer contains more than one set bit, it's still covered in at least one of the cases, and the bitwise and will still be non-zero. All that remains is counting the number of elements in the range $[l \ldots r]$ with the $b$-th bit set, for all $b$. This can be done with precomputation, by creating $b$ prefix sum arrays before answering any of the test cases, where the $i$-th element of the $b$-th array is the number of integers $\leq i$ that have the $b$-th bit on. After this, you can use the prefix sum technique to answer queries, as $cnt_b = a_{b, r} - a_{b, l}$, if $a_b$ is the $b$-th array. Challenge: solve the problem with $1 \leq l \leq r \leq 10^9$.
[ "bitmasks", "greedy", "math" ]
1,300
null
1615
C
Menorah
There are $n$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $s$, where the $i$-th candle is lit if and only if $s_i=1$. Initially, the candle lights are described by a string $a$. In an operation, you select a candle that is \textbf{currently lit}. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit). You would like to make the candles look the same as string $b$. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.
First, let's define the "type" of a candle $i$ to be the string $a_ib_i$. For example, if a candle is currently unlit and must be lit in the end, its type is $01$. It's useful to think about the number of candles of each type because the position of a candle is irrelevant in this problem. Now, let's consider what happens when we do two operations consecutively. All candles except the ones we select will flip twice, so let's focus on what happens to the candles we select. If we select the same candle twice, nothing changes. And if we select two different candles, it's equivalent to swapping a $1$ and a $0$ in the string. Since we have a really nice description of two consecutive operations, any sequence of an even number of operations is just a sequence of swaps. So it's possible in an even number of operations as long as the number of $1$'s in both strings is the same, and the minimum number of operations will be the number of positions where the strings differ. Now, what about an odd number of operations? Well, it's the same as performing one operation and then reducing it to the case of an even number of operations. There are two types of candles we can select on the first operation: type $10$ and type $11$. Simply try both options if they're present, and find the minimum number of operations after it's reduced to the even case. Finally, there are some strings where it's possible to do in either an even or an odd number of operations, so in those cases we have to take the minimum of both options. The total complexity is $O(n)$. Bonus: Can you prove that in the case of an odd number of operations, it is never necessary to select a candle of type $10$?
[ "brute force", "graphs", "greedy", "math" ]
1,600
null
1615
D
X(or)-mas Tree
'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are $n$ nodes in the tree, connected by $n-1$ edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation. He has $m$ elves come over and admire his tree. Each elf is assigned two nodes, $a$ and $b$, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the bitwise XOR of the values of the lights on the edges in that path. However, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned $(a_i, b_i)$, as well as \textbf{the parity} of the number of set bits in his favorite number. In other words, he remembers whether the number of $1$'s when his favorite number is written in binary is \textbf{odd or even}. Help Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history!
Let $\text{count}(x)$ be the number of $1$-bits in an integer $x$. Notice that $\text{count}(x \oplus y)\mod 2$ = $\text{count}(x) \mod 2 \oplus \text{count}(y) \mod 2$. This means that you can replace each integer $x$ on the tree with $\text{count}(x) \mod 2$. Note that you can pretend the initial given edges are also just elves who traveled over the path consisting solely of that edge. After this transformation, each of the edge weights is either $0$ or $1$, and you're given a set of paths and you are told the XOR of each path. Root the tree at node $1$. Let $r_i$ be the XOR of the values on the edges from node $i$ to the root ($r_1 = 0$). Notice that the XOR of a path $(a, b)$ is $r_a \oplus r_b$. From this, each constraint of the form $(a, b, c)$ telling you that the XOR of the path $(a, b)$ has to equal $c$ is equivalent to $r_a \oplus r_b = c$. This problem can be solved using a variant of bipartite coloring, where you create a graph and add a bidirectional edge between $(a, b)$ with weight $c$ for each of those constraints. You run dfs through each of the individual connected components. Within a component, choosing the value of a single node uniquely determines the rest. During the dfs, if you're at a node $a$ and are considering traversing the edge $(a, b, c)$, you know that $r_b = r_a \oplus c$, so you can determine $r_b$ from $r_a$. The final value of an edge between $a$ and $p$ (the parent of $a$) is $r_a \oplus r_p$.
[ "bitmasks", "dfs and similar", "dsu", "graphs", "trees" ]
2,200
null
1615
E
Purple Crayon
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game. The game works as follows: there is a tree of size $n$, rooted at node $1$, where each node is initially white. Red and Blue get \textbf{one turn each}. Red goes first. In Red's turn, he can do the following operation \textbf{any number of times}: - Pick any subtree of the rooted tree, and color every node in the subtree red. However, to make the game fair, Red is only allowed to color $k$ nodes of the tree. In other words, after Red's turn, at most $k$ of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation \textbf{any number of times}: - Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon. Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let $w$ be the number of white nodes, $r$ be the number of red nodes, and $b$ be the number of blue nodes. The score of the game is $w \cdot (r - b)$. Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?
After expanding the expression given in the statement (by replacing $w$ with $n - r - b$), it reduces to $r \cdot (n - r) - b \cdot (n - b)$. This means that in Blue's turn, his only goal is to maximize $b \cdot (n - b)$. To maximize the value of that function, it's optimal to pick the value of $b$ that is closest to $\lfloor \frac{n}{2} \rfloor$. One thing to note is that if it's possible for Blue to color exactly $x$ nodes, for some number $x$, it is possible for Blue to color exactly $x-1$ nodes as well. This is because, given some subtree that he has colored, he can also choose to color every node in the subtree except the root. This would reduce the number of Blue nodes by exactly $1$. By repeating this process, one can show that if Blue can color exactly $x$ nodes, Blue can also color $y$ nodes if $y \leq x$. What this implies is that if you know the number of nodes that Red colors, Red's optimal strategy would be to minimize the maximum number of nodes that Blue can color (as it reduces the possible choices that Blue has). If Red chooses node $x$, it means that Blue can't choose any ancestors (or descendants) of node $x$. This transforms the problem into the following: For all $i \leq k$, perform the following operation exactly $i$ times: choose a node $v$ and mark all of the nodes on the path to the root. For each $i$, calculate the maximum number of nodes that are marked at least once at the end of this process by optimally choosing $v$ at each step. The set of optimally chosen $v$ (for a given $i$) can be found using the following greedy algorithm: Sort all nodes in decreasing order of depth. Then, go through the nodes in order, let the current node be $v$. Go to the root marking nodes until you reach one that has already been marked. Let the number of marked nodes be $c_v$. Finally, sort all nodes in decreasing order of $c_v$. Choose the first $i$ nodes from this list. Proof that the greedy produces the correct answer: We must prove that the greedy algorithm always chooses a subset of nodes that maximizes the number of marked nodes at the end of the process. We can imagine that instead of coloring nodes, we can delete them from the tree to get a forest of rooted trees. Let's prove that there is an optimal solution where the deepest leaf in a forest (say $v$) is chosen. Consider a configuration in which $v$ is not chosen. Let $u$ be the node that maximizes the depth of LCA($u$, $v$) that is present in the configuration. You can replace the node $u$ with $v$ in the configuration, and the answer won't decrease (as the depth of $v$ is greater than the depth of $u$). Since the relative order of depths in a tree in the forest at any point is the same as the relative order of depths of its vertices in the original tree, choosing the deepest node in a tree in the forest is equivalent to choosing the vertex in that tree, which has the max depth in the original tree. Note that the process can be simulated in amortized linear time (not including the sorting), as each node will be colored at most once. All that's left is to iterate over all values of $i$, and take the maximum value that Red can get.
[ "data structures", "dfs and similar", "games", "graphs", "greedy", "math", "sortings", "trees" ]
2,400
null
1615
F
LEGOndary Grandmaster
After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $1$ and length $n$, some positions of which are occupied by $1$ by $1$ Lego pieces. In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues. You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend $0$ seconds). The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo $1\,000\,000\,007$ ($10^9 + 7$).
First, let's consider a fixed pair of strings $s$ and $t$, and find a simple way to calculate the amount of time it takes. Key observation: Flip every bit at an even position in both strings $s$ and $t$. Now, the operation is equivalent to swapping two adjacent bits of $s$. This is because the operation is equivalent to flipping two adjacent bits and swapping them. Flipping bits on an even position takes care of the first part of the operation (as any operation includes one bit at an even and one bit at an odd position), so the problem reduces to simple swapping. Now, for a fixed pair of strings, you want to find the minimum number of swaps to transform one into the other. Obviously, the answer is $0$ if the number of 1's in both strings is different. Now, let the number of 1's in each string be $k$, and the position of the $i$-th 1 from the left in $s$ be $x_i$, and the $i$-th 1 from the left in $t$ be $y_i$. The answer for a fixed pair of strings is $\sum\limits_{i = 1}^k|x_i - y_i|$, as the $i$-th 1 in $s$ will always be matched with the $i$-th 1 in $t$. This expression can be transformed into a more convenient one. Let $a_i$ be the number of 1's in $s$ in the prefix ending at $i$, and $b_i$ the number of 1's in $t$ in the prefix ending at $i$. The previous expression is equivalent to $\sum\limits_{i = 1}^n|a_i - b_i|$. This is because the $i$-th index contributes $1$ to each 1 in the previous expression if and only if a $1$ needs to "cross" the $i$-th index when moving to it's corresponding location in $t$. Exactly $|a_i - b_i|$ 1's will cross over the index, so the answer is the sum over all of the values. Now going back to the original problem, apply the initial transformation on the strings $s$ and $t$, where for each even index, you change 0 to 1, 1 to 0, and keep ? the same. Let $p_{i, j}$ be the number of ways, if you only consider indices $\leq i$, to replace the ?'s with 0's and 1's so that $a_i - b_i = j$. $s_{i, j}$ is defined similarly, except you only consider indices $\geq i$. Both of these have $\mathcal{O}(n^2)$ states and $\mathcal{O}(1)$ transitions. The final answer is $\sum\limits_{i=1}^{n-1} \sum\limits_{j=-n}^n |\ j \cdot p_{i, j} \cdot s_{i+1, -j} \ |$.
[ "combinatorics", "dp", "math" ]
2,800
null
1615
G
Maximum Adjacent Pairs
You are given an array $a$ consisting of $n$ non-negative integers. You have to replace each $0$ in $a$ with an integer from $1$ to $n$ (different elements equal to $0$ can be replaced by different integers). The value of the array you obtain is the number of integers $k$ from $1$ to $n$ such that the following condition holds: there exist a pair of adjacent elements equal to $k$ (i. e. there exists some $i \in [1, n - 1]$ such that $a_i = a_{i + 1} = k$). If there are multiple such pairs for some integer $k$, this integer is counted in the value only once. Your task is to obtain the array with the maximum possible value.
Let's consider each segment of zeroes in our sequence. Each of these segments has either odd or even length. If a segment has length $2m + 1$ (it is odd), then it can be used to create $m$ pairs of neighboring elements, and an additional pair for either the number right before the segment, or for the number right after the segment. If a segment has length $2m$ (it is even), then it can be used either to create $m$ pairs of neighboring elements, or $m-1$ pairs of any integers and two additional pairs for the elements that are on the borders of the segment. It's never optimal to match only one of the zeroes in an even segment with the element on the border, because we could just use the segment to create $m$ pairs instead. Let's build an undirected graph which initially has $m = \max\limits_{i=1}^{n} a_i$ vertices (one for each integer from $1$ to $m$). Let's add the following edges and vertices to it: For each integer already having a pair of adjacent elements, add an auxiliary vertex and connect it with the vertex representing the integer. For each $0$-segment of even length, add an edge between vertices representing elements on the borders of this segment (we need at most one of these for each pair of elements on the border). For each $0$-segment of odd length, add an auxiliary vertex and connect it with vertices representing elements on the borders of this segment (we need at most two of these for each pair of elements on the border). Let's find the maximum matching in this graph using some maximum matching algorithm (for example, Edmonds' blossom algorithm). Let the size of the maximum matching be $M$. It can be shown that the sum of $M$ and all values $\lfloor \frac{len}{2} \rfloor$ over all $0$-segments (where $len$ is the length of the segment) is equal to the maximum number of integers that can have a pair of neighboring elements: for each segment of even length, the edge representing it will either be in the matching (and the segment will create $\frac{len}{2} + 1$ pairs), or the edge won't belong to the matching (and the segment will create $\frac{len}{2}$ pairs). For each odd $0$-segment, we either match its vertex with a number on its border (so this segment creates $\frac{len - 1}{2} + 1$ pairs), or won't match its vertex (so this segment creates $\frac{len - 1}{2}$ pairs). The numbers already having a pair of neighboring elements will be processed by the vertices connected only to them, so they get $+1$ to the size of the matching "for free" and can't be matched with anything else (or will be matched, but won't add $+1$ for free). The maximum matching can enforce the constraint that each number is counted in the answer only once. How fast will this solution work? Unfortunately, it can be too slow. The resulting graph can have up to $O(n)$ edges and up to $600^2$ vertices, so the standard implementation of Edmonds is not sufficient. But there are many different heuristics you can use in this problem to speed up the solution. We used the following one: Split all vertices into two "parts", the first part will contain the vertices representing the numbers, and the second part will contain all of the other vertices. The edges can connect only vertices from the first part and the vertices from different parts, and there are only up to $600$ vertices in the first part. Let's ignore the edges between the vertices in the first part and find the maximum matching in this graph using Kuhn's algorithm. Then, we claim that if we find the maximum general matching starting from this bipartite matching and improving it, the augmenting paths cannot both start and end in the vertices of the second part (since the number of matched vertices in the second part cannot exceed the maximum bipartite matching). Then we can search for augmenting paths only starting in vertices of the first part in Edmonds (so we need only $600$ phases of Edmonds). Furthermore, we can speed up each phase of Edmonds as follows: if the current size of the matching is $M$, then we'll visit no more than $2M+2$ vertices while searching for an augmenting path; and if we contract each blossom in linear time of its size, each phase will work in $O(M^2)$, where $M$ is the current size of the matching (and it cannot me greater than $600$).
[ "constructive algorithms", "graph matchings" ]
3,300
null
1615
H
Reindeer Games
There are $n$ reindeer at the North Pole, all battling for the highest spot on the "Top Reindeer" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the "Top Reindeer" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer games, but they still give it the utmost importance. Currently, the $i$-th reindeer has a score of $a_i$. You would like to influence the leaderboard with some operations. In an operation, you can choose a reindeer, and either increase or decrease his score by $1$ unit. Negative scores are allowed. You have $m$ requirements for the resulting scores. Each requirement is given by an ordered pair $(u, v)$, meaning that after all operations, the score of reindeer $u$ must be less than or equal to the score of reindeer $v$. Your task is to perform the minimum number of operations so that all requirements will be satisfied.
Let's try to find a nice lower bound for the answer. Let's denote a requirement of two nodes $u$ and $v$ by a directed edge $u\to v$. We can observe that if there are two nodes $u$ and $v$ such that there's a requirement $u\to v$ (or a path of requirements from $u$ to $v$), then we will need to do at least $a_u-a_v$ operations on these two nodes. So, if we can create a list of pairs $(u_1,v_1),\ldots, (u_k,v_k)$ with all distinct nodes such that there is a path from $u_i$ to $v_i$ for all $i$, then a lower bound of the answer is $\sum\limits_{i=1}^k (a_{u_i}-a_{v_i})$ Our strategy will be to find the largest possible lower bound of this form, and then construct a solution with exactly that cost (which is therefore the optimal cost). To find an optimal set of pairs, we can set it up as a flow problem. Every directed edge $u\to v$ of the original graph will have infinite capacity and a cost of $a_u-a_v$. In addition, we will create two new nodes $s$ and $t$. For each node $u$, add an edge $s\to u$ with capacity $1$ and cost $0$, and add an edge $u\to t$ with capacity $1$ and cost $0$. Compute the maximum cost flow from $s$ to $t$ (the amount of flow doesn't need to be maximized). If there is any node $u$ such that $s\to u$ and $u\to t$ both have flow, make them both have $0$ flow, and this won't change the cost. The flow can be decomposed into paths with distinct endpoints in the original graph. The endpoints are distinct because each node $u$ cannot have flow on both edges $s\to u$ and $u\to t$. And the cost of a path beginning in $u$ and ending in $v$ will be $a_u-a_v$ (intermediate nodes of the path cancel out when computing the cost). It's also easy to see that any set of pairs has a corresponding flow in the graph with the same cost. So, this flow gives us a way to compute a set of pairs with the maximum lower bound, just like we want. Now, how do we construct the operations to perform? First, take the edges of the residual flow graph that are not at full capacity. Using only these edges, compute the longest path from $s$ to every node in the graph (where length of a path is the sum of edge costs). Let's say the longest path from $s$ to $u$ is $d_u$. Let's show that $b_u:=a_u+d_u$ satisfies all requirements. Every requirement $u\to v$ is present in the residual graph because it has infinite capacity. So we have that $d_u+(a_u-a_v)\le d_v$, otherwise we could find a longer path from $s$ to $v$. By moving $a_v$ to the right side of this inequality, we get $a_u+d_u\le a_v+d_v$, In other words, $b_u\le b_v$, meaning this requirement is satisfied. Let's show that the total number of operations $\sum_u|b_u-a_u|$ does not exceed the cost of the flow. It's sufficient to show that for each node $u$ that isn't in one of the pairs, we have $b_u=a_u$, and for each pair $(u_i, v_i)$ we have that $a_{v_i}\le b_{v_i}=b_{u_i}\le a_{u_i}$. For the first part, suppose a node $u$ is unpaired. If $d_u>0$, then there is a path from $s$ to $u$ with positive cost, and there is an edge from $u$ to $t$ of $0$ cost because it's unpaired, so we've found an augmenting path in the flow graph that will increase the cost. This contradicts the fact that we found the maximum cost flow. On the other hand, if $d_u<0$, this contradicts the definition of $d_u$ since there's an edge $s\to u$ of cost $0$ which makes a longer path. Therefore, $d_u=0$ and $b_u=a_u+d_u=a_u$, as desired. For the second part, consider a pair $(u_i,v_i)$. There is a path in the residual graph from $v_i$ to $u_i$, so we have $d_{v_i}+(a_{v_i}-a_{u_i})\le d_{u_i}$. In other words, $b_{v_i}\le b_{u_i}$. But we already had that $b_{u_i}\le b_{v_i}$ because all requirements are satisfied, therefore $b_{u_i}=b_{v_i}$. It's impossible to have $d_{v_i}<0$ because there's a longer path with the direct edge $s\to v_i$ which is present in the residual graph. It's impossible to have $d_{u_i}>0$ because it would mean the edge $u_i\to t$ creates an augmenting path with positive cost. Therefore, $a_{v_i}\le a_{v_i}+d_{v_i}=b_{v_i}=b_{u_i}=a_{u_i}+d_{u_i}\le a_{u_i}$, as desired. In summary, the solution is to build a flow graph, compute the maximum cost flow (which is equivalent to minimum cost flow with all costs negated), and compute the distance values $d_u$ to construct the solution. The flow can be computed with the potential method in $O(nm\log n)$ time.
[ "binary search", "constructive algorithms", "data structures", "divide and conquer", "flows", "graphs", "shortest paths" ]
3,000
null
1616
A
Integer Diversity
You are given $n$ integers $a_1, a_2, \ldots, a_n$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $x \to (-x)$). What is the maximum number of different values in the array you can achieve?
At first, let's replace $a_i$ with $|a_i|$. Let $f(x)$ denote the number of vaues in the array equal to $x$ after the replacement (or, equal to $x$ or $-x$ before). Then, for the zero we can only get $\min(1, f(0))$ different values. And for any other number $x > 0$, we can get $\min(2, f(x))$ different numbers in the array. As different absolute values are independent and bounded, to get the answer we just need to evalue the sum $\min(1, f(0)) + \min(2, f(1)) + \ldots + \min(2, f(100))$. It can be easily done using arrays, maintaning the number of occurences for each $|x|$.
[ "implementation" ]
800
null
1616
B
Mirror in the String
You have a string $s_1 s_2 \ldots s_n$ and you stand on the left of the string looking right. You want to choose an index $k$ ($1 \le k \le n$) and place a mirror after the $k$-th letter, so that what you see is $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$. What is the lexicographically smallest string you can see? 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$.
Let's compare $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$ and $s_1 s_2 \ldots s_{k+1} s_{k+1} s_{k} \ldots s_1$. Note that they have a long common prefix $s_1, s_2, \ldots, s_k$. And the next pair of characters to compare is $s_{k+1}$ and $s_k$. So, unless $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$ is a prefix of $s_1 s_2 \ldots s_{k+1} s_{k+1} s_{k} \ldots s_1$, it is optimal to choose $k+1$ if $s_{k+1} \leq s_k$. Pushing this idea further, we can see that the answer is either $s_1 s_1$ or $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$, for the largest $k$ such that $s_k \leq s_{k-1}$.
[ "greedy", "strings" ]
1,100
null
1616
C
Representative Edges
An array $a_1, a_2, \ldots, a_n$ is good if and only if for every subsegment $1 \leq l \leq r \leq n$, the following holds: $a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$. You are given an array of integers $a_1, a_2, \ldots, a_n$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.
Note that if the array is good $a_{k+2}-a_{k+1}=a_{k+1}-a_k$. In other words, the array form an arithmetic progression. We can either fix an arbitrary element and set all other elements equal to it (giving us the lower bound $n-1$ on the answer). Or, to solve the remaining case, we can fix any two elements that are in the answer, derive the formula for an arbitrary element of the arithmetic progression, and check the number of elements that we have to change.
[ "brute force", "geometry", "implementation", "math" ]
1,500
null
1616
D
Keep the Average High
You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $x$. You need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \ldots, a_r$ containing strictly more than one element $(l < r)$, either: - At least one element on this subsegment is \textbf{not} selected, or - $a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1)$.
Note that $a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1) \Rightarrow (a_l - x) + (a_{l+1} - x) + \ldots + (a_r - x) \geq 0$. After subtracting $x$ from all elements, the problem is reduced to choosing the maximum number of elements with only non-negative sum contiguous elements. Note that there should be a negative-sum subsegment of length $2$ or $3$, if there is a negative-sum subsegment. It is easy to see as $x < 0, y < 0 \Rightarrow x + y < 0$. Hence, to solve the original problem we can use a simple DP, storing for the last two elements whether they are in the answer or not.
[ "dp", "greedy", "math" ]
2,000
null
1616
E
Lexicographically Small Enough
You are given two strings $s$ and $t$ of equal length $n$. In one move, you can swap any two adjacent characters of the string $s$. You need to find the minimal number of operations you need to make string $s$ lexicographically smaller than string $t$. 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$.
Let's iterate over characters one by one and see the minimum number of operations required to make the string smaller with the fixed common prefix. Every time, we need to update the answer with the minimum number of moves required to make our prefix equal to some other prefix (iterating over characters smaller than the current). In general, we can easily see that the optimal strategy is to move characters one by one, every time choosing the closest character. You can use data structures like Binary Indexed Tree to maintain the answer along the way.
[ "brute force", "data structures", "greedy", "strings" ]
2,200
null
1616
F
Tricolor Triangles
You are given a simple undirected graph with $n$ vertices and $m$ edges. Edge $i$ is colored in the color $c_i$, which is either $1$, $2$, or $3$, or left uncolored (in this case, $c_i = -1$). You need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices $1 \leq a < b < c \leq n$, the colors of the edges $a \leftrightarrow b$, $b \leftrightarrow c$, and $a \leftrightarrow c$ are either pairwise different, or all equal. In case no such coloring exists, you need to determine that.
$c_1, c_2, c_3$ form a valid triangle coloring if and only if $c_1 + c_2 + c_3 = 3k$ for some $k \in \mathbb{Z}$ Hence we can solve our problem with the simple Gaussian elemeniation. Complexity depends on your implementation, and you can use bitset to optimize it by $64$ times. Note that the number of triangles is bounded by $m\sqrt{m}$, and the number of elements in the basis is $m$.
[ "brute force", "graphs", "math", "matrices" ]
2,900
null
1616
G
Just Add an Edge
You are given a directed acyclic graph with $n$ vertices and $m$ edges. For all edges $a \to b$ in the graph, $a < b$ holds. You need to find the number of pairs of vertices $x$, $y$, such that $x > y$ and after adding the edge $x \to y$ to the graph, it has a Hamiltonian path.
First of all, we have to check whether there is a Hamiltonian path in the original graph. In this case, the number is ${n \choose 2}$ Otherwise, addition of the edge $a \to b$ can only add a Hamiltonian path of the form: $(1 \to \ldots \to a - 1) \to \ldots \to b$ $b \to a$ $a \to \ldots \to (b \to \ldots n)$ And these paths should be non-intersecting. Where $(x \to \ldots \to y)$ means the default path $x \to (x+1) \to \ldots \to y$ Using this observation, it is easy to derive a $DP$ with two states: two last vertices on the chain, and we are only interested in the states where $x,x+1$ are in different chains. $dp_{x,x+1}, dp_{x+1,x}$, we are interested in the number of valid pairs $(a-1,a)$ that you can reach from the valid pair $(b,b+1)$. Pair is valid if there is a hamilton path in the required direction. From here, we can get a solution in $O(nm)$, that could be optimized with bitset to $O(\frac{nm}{64})$. But to make it linear, let's note that if there is no Hamiltonian path, then there is some edge $y \to (y+1)$ not present in the graph, and all the paths connecting the pairs oof vertices we are interested in are going through this edge. So instead of maintaining the set of all valid $(a,a+1)$, we can run DFS in two drections from $(y,y+1)$, and calculate the number of required pairs.
[ "dfs and similar", "dp", "graphs" ]
3,500
null
1616
H
Keep XOR Low
You are given an array $a_1, a_2, \ldots, a_n$ and an integer $x$. Find the number of non-empty subsets of indices of this array $1 \leq b_1 < b_2 < \ldots < b_k \leq n$, such that for all pairs $(i, j)$ where $1 \leq i < j \leq k$, the inequality $a_{b_i} \oplus a_{b_j} \leq x$ is held. Here, $\oplus$ denotes the bitwise XOR operation. As the answer may be very large, output it modulo $998\,244\,353$.
First of all, we should divide all elements into groups by the prefix before the leading bit $i$ of $x$, as elements from different groups will definitely yield invalid answers. In one group, we either choose elements only from the group with the same bit $i$, then we can choose an artbirary subset. Or we need to solve the following problem: You are given two sequences $a,b$ of lengths $n,m$ and the current bit $i$. Choose any subset of $a \cup b$, such that in each sequence at least one element is chosen, and the bitwise XOR of any pair (ignoring bits above $i$) is at most $x$ To solve this problem, we need to look at the bit $i$ in $x$. If it is set to zero, we need to recursively divide both arrays into $a_0, a_1, b_0, b_1$ according to the bits, and multiply the answers of $(a_0, b_0,i+1)$, and $(a_1, b_1, i+1)$. Otherwise, let's note that $(a_0, b_1)$ and $(a_1, b_0)$ are independent, so we can multiply their answers and also add a bunch of simple combinatorial formulas in case none elements are chosen in one of these pairs. The total complexity is $O(30n)$, as at each layer there are only $n$ elements in total.
[ "bitmasks", "combinatorics", "data structures", "divide and conquer", "dp", "math" ]
3,000
null
1617
A
Forbidden Subsequence
You are given strings $S$ and $T$, consisting of lowercase English letters. It is guaranteed that $T$ is a permutation of the string abc. Find string $S'$, the \textbf{lexicographically smallest} permutation of $S$ such that $T$ is \textbf{not} a subsequence of $S'$. String $a$ is a permutation of string $b$ if the number of occurrences of each distinct character is the same in both strings. A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. 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$.
When is the lexicographically smallest permutation of $S$ (i.e. the sorted string) not the answer? If there are no occurrences of a, b or c in $S$, sort $S$ and output it. Else, if $T \ne$ abc, sort $S$ and output it. Else, output all a, then all c, then all b, then the rest of the string sorted. Originally, the author and two testers' solutions are all wrong, but we didn't notice until the third tester submitted the real correct solution.
[ "constructive algorithms", "greedy", "sortings", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define all(x) x.begin(), x.end() int main() { int T; cin >> T; while(T--) { string s, t; cin >> s >> t; sort(all(s)); vector<int> cnt(26, 0); for(auto x: s)cnt[x - 'a']++; if(t != "abc" || !cnt[0] || !cnt[1] || !cnt[2])cout << s << "\n"; else{ while(cnt[0]--)cout<<"a"; while(cnt[2]--)cout<<"c"; while(cnt[1]--)cout<<"b"; for(int i = 3;i < 26; ++i){ while(cnt[i]--)cout<<char('a' + i); } cout << "\n"; } } }
1617
B
GCD Problem
Given a positive integer $n$. Find three \textbf{distinct} positive integers $a$, $b$, $c$ such that $a + b + c = n$ and $\operatorname{gcd}(a, b) = c$, where $\operatorname{gcd}(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
There must exist a solution for $c=1$ under the given constraints. Key observation: there always exists a solution with $c = 1$ under the given constraints. We set $n \ge 10$ because there is no solution when $1 \le n \le 5$ or $n = 7$. Solution 1: Brute force from $a = 2, 3, 4, \dots$ and calculate the value of $b$ ($b = n - a - 1$), then check whether $gcd(a, b) = 1$. It works, because you will find a prime number $p \le 29$ such that $n-1$ does not divide $p$. Solution 2: Randomly choose $a$ and calculate $b$ ($b = n - a - 1$). Repeating that for enough times will eventually get you a pair of ($a, b$) such that $gcd(a, b) = 1$. Solution 3: Constructive solution. When $n \equiv 0 \pmod 2$, output ($n-3, 2, 1$). When $n \equiv 0 \pmod 2$, output ($n-3, 2, 1$). When $n \equiv 1 \pmod 4$, output ($\left \lfloor \frac{n}{2} \right \rfloor -1, \left \lfloor \frac{n}{2} \right \rfloor +1, 1$). When $n \equiv 1 \pmod 4$, output ($\left \lfloor \frac{n}{2} \right \rfloor -1, \left \lfloor \frac{n}{2} \right \rfloor +1, 1$). When $n \equiv 3 \pmod 4$, output ($\left \lfloor \frac{n}{2} \right \rfloor -2, \left \lfloor \frac{n}{2} \right \rfloor +2, 1$). When $n \equiv 3 \pmod 4$, output ($\left \lfloor \frac{n}{2} \right \rfloor -2, \left \lfloor \frac{n}{2} \right \rfloor +2, 1$).
[ "brute force", "constructive algorithms", "math", "number theory" ]
900
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin>>n; if (n%2==0) cout<<"2 "<<(n-1)-2<<" 1\n"; else { int cur=(n-1)/2; if (cur%2==0) cout<<cur-1<<" "<<cur+1<<" "<<1<<endl; else cout<<cur-2<<" "<<cur+2<<" "<<1<<endl; } } signed main(){ int t; cin>>t; while (t--) solve(); }
1617
C
Paprika and Permutation
Paprika loves permutations. She has an array $a_1, a_2, \dots, a_n$. She wants to make the array a \textbf{permutation} of integers $1$ to $n$. In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $i$ ($1 \le i \le n$) and $x$ ($x > 0$), then perform $a_i := a_i \bmod x$ (that is, replace $a_i$ by the remainder of $a_i$ divided by $x$). In different operations, the chosen $i$ and $x$ \textbf{can be different}. Determine the minimum number of operations needed to make the array a permutation of integers $1$ to $n$. If it is impossible, output $-1$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
For any two positive integers $x$, $y$ that satisfy $x \ge y$, what is the maximum value of $x \bmod y$? Consider the following input: $n = 4$, $a = [3, 3, 10, 10]$. Sometimes, we don't need to do anything to some $a_i$. When do we have to make operations, and when do we not have to? Key observation: $x \bmod y < \frac{x}{2}$ if $x \ge y$, and $x \bmod y = x$ if $x < y$. Notice that the bigger the $x$, the bigger the range of values that can be obtained after one $\bmod$ operation. So, intuitively, we want to assign smaller $a_i$ to smaller numbers in the resulting permutation. However, if $a_i$ satisfies $1 \le a_i \le n$, we can just leave it there and use it in the resulting permutation (if multiple $a_i$ satisfy $1 \le a_i \le n$ and have the same value, just choose one). Let's suppose in the optimal solution, we change $x$ to $y$ and change $z$ to $x$ for some $z > x > y$ ($x$, $y$, $z$ are values, not indices). Then changing $x$ to $x$ (i.e. doing nothing) and changing $z$ to $y$ uses $1$ less operation. And, if it is possible to change $z$ to $x$, then it must be possible to change $z$ to $y$. However, if it is not possible to change $z$ to $x$, it might still be possible to change $z$ to $y$. Therefore, the solution is as follows: Sort the array. For each element $i$ in the sorted array: If $1 \le a_i \le n$ and it is the first occurrence of element with value $a_i$, leave it there. If $1 \le a_i \le n$ and it is the first occurrence of element with value $a_i$, leave it there. Else, let the current least unassigned value in the resulting permutation be $m$, if $m < \frac{a_i}{2}$, we can assign the current element to value $m$ and add the number of operations by $1$. Else, output $-1$ directly. Else, let the current least unassigned value in the resulting permutation be $m$, if $m < \frac{a_i}{2}$, we can assign the current element to value $m$ and add the number of operations by $1$. Else, output $-1$ directly. The solution works in $O(n \log n)$.
[ "binary search", "greedy", "math", "sortings" ]
1,300
#include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ t--; int n; cin >> n; set<int> st; for(int i=1;i<=n;i++){st.insert(i);} vector<int> rem; for(int i=0;i<n;i++){ int v; cin >> v; if(st.find(v)!=st.end()){st.erase(v);} else{rem.push_back(v);} } sort(rem.begin(),rem.end()); reverse(rem.begin(),rem.end()); int pt=0; bool err=false; for(auto &nx : rem){ auto it=st.end(); it--; int ctg=(*it); if(ctg>(nx-1)/2){err=true;break;} st.erase(it); } if(err){cout << "-1\n";} else{cout << rem.size() << '\n';} } return 0; }
1617
D1
Too Many Impostors (easy version)
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions. There are $n$ players labelled from $1$ to $n$. \textbf{It is guaranteed that $n$ is a multiple of $3$.} Among them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is not given to you. \textbf{It is guaranteed that $\frac{n}{3} < k < \frac{2n}{3}$.} In each question, you can choose three distinct integers $a$, $b$, $c$ ($1 \le a, b, c \le n$) and ask: "Among the players labelled $a$, $b$ and $c$, are there more impostors or more crewmates?" You will be given the integer $0$ if there are more impostors than crewmates, and $1$ otherwise. Find the number of impostors $k$ and the indices of players that are impostors after asking at most $2n$ questions. The jury is \textbf{adaptive}, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.
The weird constraint, $\frac{n}{3} < k < \frac{2n}{3}$, is crucial. If you know the index of one crewmate and one impostor, how to find the roles of other $n-2$ players in exactly $n-2$ queries? Query players ($1, 2, 3$), ($2, 3, 4$), $\dots$, ($n-1, n, 1$), ($n, 1, 2$). After that, you can surely find out the index of one crewmate and one impostor. Try to find out how. Key observation: if result of query ($a, b, c$) $\ne$ result of query ($b, c, d$), since $b$ and $c$ are common, players $a$ and $d$ have different roles. Additionally, if result of query ($a, b, c$) = $1$ then player $a$ is a crewmate (and player $d$ is an impostor), vice versa. The first step is to query players ($1, 2, 3$), ($2, 3, 4$), $\dots$, ($n-1, n, 1$), ($n, 1, 2$). If the results of any two adjacent queries (or queries ($1, 2, 3$) and ($n, 1, 2$)) are different, we instantly know the roles of the two players that are only included in one query - one is a crewmate, one is an impostor. Since the number of impostors $k$ and crewmates $n-k$ satisfy $k > \frac{n}{3}$ and $n - k > \frac{n}{3}$, there must be one pair of adjacent queries that are different. After we know one crewmate and one impostor (let's call them $a$, $d$), we can query these two players with each one of the rest of the players. If a query ($a, d, x$) ($1 \le x \le n$, $x \ne a$ and $x \ne d$) returns $0$, player $x$ is an impostor, else player $x$ is a crewmate. In total, $2n-2$ queries are used.
[ "constructive algorithms", "implementation", "interactive" ]
1,800
#include <bits/stdc++.h> using namespace std; void solve() { int N; cin >> N; int res[N]; for(int i=0; i<N; i++) { cout << "? " << i + 1 << " " << (i+1) % N + 1 << " " << (i+2) % N + 1 << endl; cin >> res[i]; } vector<int> imp; for(int i=0; i<N; i++) { if(res[i] != res[(i+1) % N]) { if(res[i] == 0) imp.push_back(i + 1); else imp.push_back((i+3) % N + 1); for(int j=0; j<N; j++) { if(j != i && j != (i+3) % N) { cout << "? " << i + 1 << " " << (i+3) % N + 1 << " " << j + 1 << endl; int r; cin >> r; if(r == 0) imp.push_back(j + 1); } } break; } } cout << "! " << imp.size(); for(int x : imp) cout << " " << x; cout << endl; } int main() { int T; cin >> T; for(int i=1; i<=T; i++) { solve(); } }
1617
D2
Too Many Impostors (hard version)
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions. There are $n$ players labelled from $1$ to $n$. \textbf{It is guaranteed that $n$ is a multiple of $3$.} Among them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is not given to you. \textbf{It is guaranteed that $\frac{n}{3} < k < \frac{2n}{3}$.} In each question, you can choose three distinct integers $a$, $b$, $c$ ($1 \le a, b, c \le n$) and ask: "Among the players labelled $a$, $b$ and $c$, are there more impostors or more crewmates?" You will be given the integer $0$ if there are more impostors than crewmates, and $1$ otherwise. Find the number of impostors $k$ and the indices of players that are impostors after asking at most $n+6$ questions. The jury is \textbf{adaptive}, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.
Aim to find an impostor and a crewmate's index in $\frac{n}{3} + c$ queries, with $c$ being a small constant. Consider splitting the $n$ players into groups of $3$ (and query each group) in order to reach the goal in Hint 1. What is special about the results of the $\frac{n}{3}$ queries? Firstly query ($1, 2, 3$), ($4, 5, 6$), $\dots$, ($n-2, n-1, n$). Due to the constraint $\frac{n}{3} < k < \frac{2n}{3}$, among the results of these $\frac{n}{3}$ queries, there must be at least one $0$ and one $1$. Now, let's call a tuple ($a, b, c$) that returns $0$ a $0$-majority tuple, and vice versa. From the easy version, notice that finding one crewmate and one impostor is very helpful in determining the roles of the remaining players. Let's make use of the above observation, and pick one adjacent $0$-majority tuple and $1$-majority tuple. Let's say we picked ($i, i+1, i+2$) and ($i+3, i+4, i+5$). Then, we query ($i+1, i+2, i+3$) and ($i+2, i+3, i+4$). Among the four queries ($i, i+1, i+2$), ($i+1, i+2, i+3$), ($i+2, i+3, i+4$), ($i+3, i+4, i+5$), there must be a pair of adjacent queries with different results. From the easy version, we can directly find the index of an impostor and a crewmate. In all the above cases, we end up knowing an impostor and a crewmate using $\frac{n}{3} + 2$ queries, including the first step. You have the index of an impostor and a crewmate now, and around $\frac{2n}{3}$ queries left. Consider using at most $2$ queries to find out roles of each player in each group of $3$ from Step 1, which should add up to $\frac{2n}{3}$ queries. Make use of the information you know about each group (whether it is $0$-majority or $1$-majority). Assume a tuple (group of $3$) is $0$-majority. There are $4$ possibilities of roles of the $3$ players in the tuple, which are: impostor, impostor, impostor impostor, impostor, impostor crewmate, impostor, impostor (and its permutations) crewmate, impostor, impostor (and its permutations) In each query, reduce half of the possibilities. It remains to figure out how we can find the roles of the remaining players using $\frac{2n}{3}$ queries. For each tuple ($i, i+1, i+2$) queried in the first step, let's assume the tuple is $0$-majority (because the other case can be solved similarly). Then, there are only four possibilities: All players $i$, $i+1$, $i+2$ are impostors. All players $i$, $i+1$, $i+2$ are impostors. Player $i$ is a crewmate, players $i+1$, $i+2$ are impostors. Player $i$ is a crewmate, players $i+1$, $i+2$ are impostors. Player $i+1$ is a crewmate, players $i$, $i+2$ are impostors. Player $i+1$ is a crewmate, players $i$, $i+2$ are impostors. Player $i+2$ is a crewmate, players $i$, $i+1$ are impostors. Player $i+2$ is a crewmate, players $i$, $i+1$ are impostors. Earlier, we found the index of a crewmate and an impostor, let the index of the crewmate be $a$ and the impostor be $b$. If the tuple ($i, i+1, a$) is $1$-majority, either player $i$ or player $i+1$ is a crewmate. So, we reduced the number of possibilities to $2$. To check which player is the crewmate, query it with $a$ and $b$ like we did in the easy version. Else, either there are no crewmates or player $i+2$ is a crewmate. So, we reduced the number of possibilities to $2$. To check the role of player $i+2$, query it with $a$ and $b$ like we did in the easy version. In both cases, we use $2$ queries for each initial tuple ($i, i+1, i+2$). So, we used $n + 2$ queries in total, but we gave you a bit more, in case you used some more queries to find a crewmate and an impostor. There is one corner case we should handle: if the tuple ($i, i+1, i+2$) contains $a$ or $b$, we can just naively query for each unknown role in the tuple, since we won't use more than $2$ queries anyway.
[ "constructive algorithms", "implementation", "interactive", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; int query(int a, int b, int c) { cout << "? " << a << ' ' << b << ' ' << c << endl; int r; cin >> r; return r; } void solve(int tc) { int n; cin >> n; int a[n+1], role[n+1]; for(int i=1; i+2<=n; i+=3) a[i] = query(i, i+1, i+2); int imp, crew; for(int i=1; i<=n; i++) role[i] = -1; for(int i=1; i+5<=n; i+=3) { if(a[i] != a[i+3]) { a[i+1] = query(i+1, i+2, i+3), a[i+2] = query(i+2, i+3, i+4); for(int j=i; j<i+3; j++) { if(a[j] != a[j+1]) { if(a[j] == 0) { imp = j, crew = j+3; role[j] = 0, role[j+3] = 1; } else { imp = j+3, crew = j; role[j+3] = 0, role[j] = 1; } } } break; } } for(int i=1; i+2<=n; i+=3) { if(i == imp || i+1 == imp || i+2 == imp || i == crew || i+1 == crew || i+2 == crew) { for(int j=i; j<i+3; j++) { if(role[j] == -1) { role[j] = query(imp, crew, j); } } } else if(a[i] == 0) { if(query(i, i+1, crew) == 1) { if(query(i, imp, crew) == 0) role[i] = 0, role[i+1] = 1; else role[i] = 1, role[i+1] = 0; role[i+2] = 0; } else { role[i] = role[i+1] = 0; role[i+2] = query(i+2, imp, crew); } } else { if(query(i, i+1, imp) == 0) { if(query(i, imp, crew) == 0) role[i] = 0, role[i+1] = 1; else role[i] = 1, role[i+1] = 0; role[i+2] = 1; } else { role[i] = role[i+1] = 1; role[i+2] = query(i+2, imp, crew); } } } cout << "! "; queue<int> q; for(int i=1; i<=n; i++) if(role[i] == 0) q.push(i); cout << q.size(); while(q.size()) { cout << " " << q.front(); q.pop(); } cout << endl; } int main() { int T; cin >> T; for(int i=1; i<=T; i++) solve(i); }
1617
E
Christmas Chocolates
Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains $n$ chocolates. The $i$-th chocolate has a non-negative integer type $a_i$. Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all $a_i$ are \textbf{distinct}). Icy wants to make at least one pair of chocolates the same type. As a result, she asks her grandparents to perform some chocolate exchanges. \textbf{Before performing any chocolate exchanges}, Icy chooses two chocolates with indices $x$ and $y$ ($1 \le x, y \le n$, $x \ne y$). In a chocolate exchange, Icy's grandparents choose a non-negative integer $k$, such that $2^k \ge a_x$, and change the type of the chocolate $x$ from $a_x$ to $2^k - a_x$ (that is, perform $a_x := 2^k - a_x$). The chocolate exchanges will be stopped only when $a_x = a_y$. \textbf{Note that other pairs of equal chocolate types do not stop the procedure.} Icy's grandparents are smart, so they would choose the sequence of chocolate exchanges that \textbf{minimizes} the number of exchanges needed. Since Icy likes causing trouble, she wants to \textbf{maximize} the minimum number of exchanges needed by choosing $x$ and $y$ appropriately. She wonders what is the optimal pair $(x, y)$ such that the minimum number of exchanges needed is maximized across all possible choices of $(x, y)$. Since Icy is not good at math, she hopes that you can help her solve the problem.
Translate the problem into a graph problem. What feature of the graph is it asking about? Draw out the graph, for $a_i \le 10$. What special property does the graph have? Any specific algorithm to solve the problem (in Hint 1)? In graph terms, the problem is as follows: in a graph with infinite nodes, two nodes $x$ and $y$ are connected if $x + y = 2^k$ for some $k \ge 0$. Among $n$ special nodes, find the pair of nodes ($i, j$) with maximum shortest distance. Here comes the key observation: For any $i \ge 1$, there exists only one $j$ ($0 \le j < i$) such that $i + j = 2^k$ for some $k \ge 0$. The proof is as follows: let's say that $0 \le j_1, j_2 < i$, $j_1 \ge j_2$, $i + j_1 = 2^{k_1}$, $i + j_2 = 2^{k_2}$. Then, $j_1 - j_2 = 2^{k_2} \cdot (2^{k_1-k_2} - 1)$. So, $j_1 \equiv j_2 \pmod {2^{k_2}}$. Since $i \le 2^{k_2}$, $j_1 = j_2$. Then, we realize we can build a graph as follows: add an edge between $x$ and $y$ ($x, y \ge 0$) if $x + y = 2^k$ for some $k \ge 0$. Because of the first key observation, the graph must be a tree. We can root the tree at node $0$. Our problem is equivalent to finding the pair of nodes which have maximum distance in a tree, which can be solved using the diameter of tree algorithm. We can't build the entire tree as it has $10^9 + 1$ nodes. Try to notice something about the depth of the tree, then think of how this could help us solve the problem (by building the tree, or otherwise). Since $0 \le a_i \le 10^9$, it is impossible to build the entire tree. A final observation is that: Consider any node $v$ with degree $\ge 2$ in the tree, then $v > p_v$ and $p_v > p_{p_v}$, therefore $v + p_v > p_v + p_{p_v}$ ($p_x$ denotes the parent of node $x$ in the tree). Hence the depth of the tree is $\lceil \log(max(a_i)) \rceil = 30$, since there are only $\lceil \log(max(a_i)) \rceil$ possible $k$ ($0 \le k < 30$) for the sum of two nodes connected by an edge. So, there are two ways to do it: the first way is to build parts of the tree: only the $n$ given nodes and the ancestors of the $n$ nodes. There will be at most $O(n \log max(a_i))$ nodes, which should fit into the memory limit. The second way is to not build the tree at all, and calculate the LCA (Lowest Common Ancestor) of two nodes to find their distance. Since the depth of the tree is $30$, LCA of two nodes can be computed by simply checking every ancestor of both nodes. In both ways, the time complexity is $O(n \log max(a_i))$.
[ "dfs and similar", "dp", "games", "graphs", "implementation", "math", "number theory", "shortest paths", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; int f(int x){ for(int i=0;;i++){ if((1<<i)>=x){ return (1<<i)-x; } } } using pi=pair<int,int>; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; map<int,pair<pi,pi>> mp; priority_queue<int> pq; for(int i=0;i<n;i++){ int v; cin >> v; pq.push(v); mp[v].first=make_pair(0,i+1); } while(!pq.empty()){ int od=pq.top();pq.pop(); if((!pq.empty()) && od==pq.top()){continue;} if(od!=1){ int nx=f(od); pq.push(nx); pi send=mp[od].first; send.first++; if(mp[nx].first<send){ mp[nx].second=mp[nx].first; mp[nx].first=send; } else if(mp[nx].second<send){mp[nx].second=send;} } } int ra=0,rb=0,rc=-1; for(auto &nx : mp){ pair<pi,pi> tg=nx.second; if(tg.first.second==0 || tg.second.second==0){continue;} if(rc<tg.first.first+tg.second.first){ rc=tg.first.first+tg.second.first; ra=tg.first.second; rb=tg.second.second; } } cout << ra << ' ' << rb << ' ' << rc << '\n'; return 0; }
1618
A
Polycarp and Sums of Subsequences
Polycarp had an array $a$ of $3$ \textbf{positive} integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $b$ of $7$ integers. For example, if $a = \{1, 4, 3\}$, then Polycarp wrote out $1$, $4$, $3$, $1 + 4 = 5$, $1 + 3 = 4$, $4 + 3 = 7$, $1 + 4 + 3 = 8$. After sorting, he got an array $b = \{1, 3, 4, 4, 5, 7, 8\}.$ Unfortunately, Polycarp lost the array $a$. He only has the array $b$ left. Help him to restore the array $a$.
The order of elements in $a$ doesn't matter. If there is at least one correct array $a$, then we can sort it and get the answer in which $a_1 \le a_2 \le a_3$. Therefore, we can always find a sorted array. Suppose that $a_1 \le a_2 \le a_3$. Then $b_1 = a_1$, $b_2 = a_2$, $b_7 = a_1 + a_2 + a_3$. We can find $a_3$ as $b_7 - a_1 - a_2$.
[ "math", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { vector <int> b(7); for(int i = 0; i < 7; i++) cin >> b[i]; cout << b[0] << ' ' << b[1] << ' ' << b[6] - b[0] - b[1] << endl; } }
1618
B
Missing Bigram
Polycarp has come up with a new game to play with you. He calls it "A missing bigram". A bigram of a word is a sequence of two adjacent letters in it. For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba". The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard \textbf{in the same order as they appear in the word}. After that, he wipes one of them off the whiteboard. Finally, Polycarp invites you to guess what the word that he has come up with was. Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with. The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.
Consider a full sequence of bigrams for some word. The first bigram consists of letters $1$ and $2$ of the word. The second bigram consists of letters $2$ and $3$. The $i$-th bigram consists of letters $i$ and $i+1$. After one bigram is removed, there becomes two adjacent bigrams such that one consists of letters $i$ and $i+1$ and the other consists of letters $i+2$ and $i+3$. Thus, we can find the position of the removed bigram by looking for a pair of adjacent bigrams such that the second letter of the first one differs from the first letter of the second one. If there is no such pair, then the sequence of bigrams represents a valid word of length $n-1$. We can append it with any bigram that starts with the second letter of the last bigram to make it a valid word of length $n$. If there exists such a pair, then all letters of the word can be recovered. We can find the position of the removed bigram, determine the letters it consisted of and insert it into the sequence. After that, we have a full sequence of bigrams and we can restore the word from it. Overall complexity: $O(n)$ per testcase.
[ "implementation" ]
800
for _ in range(int(input())): n = int(input()) s = input().split() for i in range(n - 3): if s[i][1] != s[i + 1][0]: s.insert(i + 1, s[i][1] + s[i + 1][0]) break else: s.append(s[-1][1] + 'a') print(s[0][0], end="") for i in range(n - 1): print(s[i][1], end="") print()
1618
C
Paint the Array
You are given an array $a$ consisting of $n$ positive integers. You have to choose a positive integer $d$ and paint all elements into two colors. All elements which are divisible by $d$ will be painted red, and all other elements will be painted blue. The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $d$ which yields a beautiful coloring, or report that it is impossible.
What does it mean that no pair of adjacent elements should have the same color? It means that either all elements on odd positions are blue and all elements on even positions are red, or vice versa. So, we need to check these two cases. Let's try to solve a case when we have to find a number $d$ such that $a_1, a_3, \dots$ are divisible by $d$, and $a_2, a_4, \dots$ are not. What does it mean that $d$ divides all of the numbers $a_1, a_3, \dots$? It means that $d$ divides the $gcd(a_1, a_3, \dots)$, where $gcd$ represents the greatest common divisor. Let's calculate this $gcd$ using Euclidean algorithm or some built-in functions in $O(n + \log A)$. Okay, now we need to check all divisors of the $gcd(a_1, a_3, \dots)$ and find if any of them does not divide $a_2, a_4, \dots$. So, we have to factorize $gcd$ and generate all of its divisors... or do we? In fact, if $gcd(a_1, a_3, \dots)$ divides any of the numbers $a_2, a_4, \dots$, then every divisor of $gcd$ also divides that number. So, the only two numbers we have to check as canditates for the answer are $gcd(a_1, a_3, \dots)$ and $gcd(a_2, a_4, \dots)$.
[ "math" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<long long> a(n); for(int i = 0; i < n; i++) { cin >> a[i]; } vector<long long> g(a.begin(), a.begin() + 2); for(int i = 0; i < n; i++) { g[i % 2] = __gcd(g[i % 2], a[i]); } vector<bool> good(2, true); for(int i = 0; i < n; i++) { good[i % 2] = good[i % 2] && (a[i] % g[(i % 2) ^ 1] > 0); } long long ans = 0; for(int i = 0; i < 2; i++) if(good[i]) ans = max(ans, g[i ^ 1]); cout << ans << endl; } int main() { int t; cin >> t; for(int i = 0; i < t; i++) { solve(); } }
1618
D
Array and Operations
You are given an array $a$ of $n$ integers, and another integer $k$ such that $2k \le n$. You have to perform \textbf{exactly} $k$ operations with this array. In one operation, you have to choose two elements of the array (let them be $a_i$ and $a_j$; they can be equal or different, but \textbf{their positions in the array must not be the same}), remove them from the array, and add $\lfloor \frac{a_i}{a_j} \rfloor$ to your score, where $\lfloor \frac{x}{y} \rfloor$ is the maximum integer not exceeding $\frac{x}{y}$. Initially, your score is $0$. After you perform exactly $k$ operations, you add all the remaining elements of the array to the score. Calculate the minimum possible score you can get.
It's kinda obvious that we have to choose the $k$ greatest elements of the array as the denominators in the operations: suppose we haven't chosen one of them, but have chosen a lesser element as a denominator; if we swap them, the total score won't decrease. It is a bit harder to prove that the numerators of the fractions should be the next $k$ greatest elements (the elements on positions from $n - 2k + 1$ to $n - k$ in sorted order). It can be proved as follows: each fraction we will get in such a way rounds down to either $1$ or to $0$, and if we choose a lesser element as a numerator, we can decrease a fraction from $1$ to $0$, but we'll increase the sum of elements that remain in the array, so this is not optimal. All that's left is to pair the numerators and denominators. A fraction with numerator equal to denominator rounds down to $1$, any other fraction will round down to $0$, so our goal is to minimize the number of fractions having the numerator equal to the denominator. It can be done by pairing the numbers into fractions in the following way: $\frac{a_{n-2k+1}}{a_{n-k+1}}$, $\frac{a_{n-2k+2}}{a_{n-k+2}}$, ..., $\frac{a_{n-k}}{a_n}$ (assuming $a$ is sorted). So, the solution of the problem is the following: sort the array $a$, then calculate $\sum \limits_{i=1}^{n-2k} a_i + \sum\limits_{i=1}^{k} \lfloor \dfrac{a_{n-2k+i}}{a_{n-k+i}} \rfloor$.
[ "dp", "greedy", "math" ]
1,300
def solve(): n, k = map(int, input().split()) a = list(map(int, input().split())) a = sorted(a) cost = sum(a[0:n-2*k]) + sum(map(lambda x: a[x+n-2*k] // a[x+n-k], range(0, k))) print(cost) t = int(input()) for i in range(t): solve()
1618
E
Singers' Tour
$n$ towns are arranged in a circle sequentially. The towns are numbered from $1$ to $n$ in clockwise order. In the $i$-th town, there lives a singer with a repertoire of $a_i$ minutes for each $i \in [1, n]$. Each singer visited all $n$ towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the $i$-th singer got inspired and came up with a song that lasts $a_i$ minutes. The song was added to his repertoire so that he could perform it in the rest of the cities. Hence, for the $i$-th singer, the concert in the $i$-th town will last $a_i$ minutes, in the $(i + 1)$-th town the concert will last $2 \cdot a_i$ minutes, ..., in the $((i + k) \bmod n + 1)$-th town the duration of the concert will be $(k + 2) \cdot a_i$, ..., in the town $((i + n - 2) \bmod n + 1)$ — $n \cdot a_i$ minutes. You are given an array of $b$ integer numbers, where $b_i$ is the total duration of concerts in the $i$-th town. Reconstruct any correct sequence of \textbf{positive} integers $a$ or say that it is impossible.
First, $b_i = a_i + 2 \cdot a_{i - 1} + \dots + i \cdot a_1 + (i + 1) \cdot a_n + \dots n \cdot a_{i + 1}$. Consider the sum $b_1 + b_2 + \cdots + b_n$. If we substitute the formula of $b_i$ then for every $i = 1, 2, \dots, n$ the coefficient at $a_i$ will be equal to $\frac{n \cdot (n + 1)}{2}$, so we can find the sum $S$ of all $a_i$: $S = a_1 + a_2 + \dots + a_n$ is equal to $\frac{2 \cdot (b_1 + b_2 + \dots + b_n)}{n \cdot (n + 1)}$. If the sum of $b_i$ isn't divisible by $\frac{n \cdot (n + 1)}{2}$, then the answer is NO. Now let's consider the difference between two neighboring towns: $b_i - b_{(i + n - 2) \mod n + 1} = a_{i - 1} + a_{i - 2} + \dots + a_{i \mod n + 1} - (n - 1) \cdot a_i = S - a_i - (n - 1) \cdot a_i = S - n \cdot a_i$, so $a_i = \frac{S - b_i + b_{(i + n - 2) \mod n + 1}}{n}$. If the value of $a_i$ we found isn't a positive integer, then the answer if NO. Otherwise, we can find a single value of $a_i$ for every $i = 1, 2, \dots n$. It's easy to see that these values are correct. Overall complexity: $O(n)$ per testcase.
[ "constructive algorithms", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; using li = long long; const int N = 50013; int b[N]; int a[N]; void solve() { int n; cin >> n; li sumb = 0; for(int i = 0; i < n; i++) { cin >> b[i]; sumb += b[i]; } li d = n * 1ll * (n + 1) / 2; if(sumb % d != 0) { cout << "NO" << endl; return; } li suma = sumb / d; for(int i = n - 1; i >= 0; i--) { li res = (b[i] - b[(i + 1) % n] + suma); if(res % n != 0 || res <= 0) { cout << "NO" << endl; return; } a[(i + 1) % n] = res / n; } cout << "YES" << endl; for(int i = 0; i < n; i++) cout << a[i] << ' '; cout << endl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
1618
F
Reverse
You are given two positive integers $x$ and $y$. You can perform the following operation with $x$: write it in its binary form without leading zeros, add $0$ or $1$ to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of $x$. For example: - $34$ can be turned into $81$ via one operation: the binary form of $34$ is $100010$, if you add $1$, reverse it and remove leading zeros, you will get $1010001$, which is the binary form of $81$. - $34$ can be turned into $17$ via one operation: the binary form of $34$ is $100010$, if you add $0$, reverse it and remove leading zeros, you will get $10001$, which is the binary form of $17$. - $81$ can be turned into $69$ via one operation: the binary form of $81$ is $1010001$, if you add $0$, reverse it and remove leading zeros, you will get $1000101$, which is the binary form of $69$. - $34$ can be turned into $69$ via two operations: first you turn $34$ into $81$ and then $81$ into $69$. Your task is to find out whether $x$ can be turned into $y$ after a certain number of operations (possibly zero).
There are two main approaches to this problem. Approach $1$. Let's analyze how the binary representation of $x$ changes after the operation. If there are no zeroes at the end of it, appending $0$ just reverses the binary representation; if there are any trailing zeroes, we remove them and reverse the binary representation. If we append $1$, we just reverse the binary representation and add $1$ at the beginning. No matter which action we choose on the first step, the resulting binary representation will have $1$ at its beginning and $1$ at its end, so no bits can be removed from it (no zero from the resulting binary representation can become leading). It means that every number we can obtain from $x$ will have the following form: several ones (maybe none), then $s$, then several ones (again, maybe none), where $s$ is one of the following four strings: the binary representation of $x$ after appending $1$ in the first operation; the binary representation of $x$ after appending $0$ in the first operation; one of the aforementioned representations, but reversed. We can check that $y$ meets one of these four templates, but since we only considered the case when we apply at least one operation, we also have to verify if $x = y$. Approach $2$. Run something like implicit BFS or DFS to generate all possible values you can obtain, pruning when the length of the binary representation we get becomes too large (say, greater than $100$). Why does this work fast? As we have shown in our first approach, the numbers we can get from $x$ have a very specific form, and if we limit their lengths to $100$, we will consider only about $400$ different numbers. Note that if you try this approach, you have to store the obtained numbers in some associative data structure (I use a set of strings in my solution).
[ "bitmasks", "constructive algorithms", "dfs and similar", "implementation", "math", "strings" ]
2,000
#include<bits/stdc++.h> using namespace std; string go(string t) { while(t.back() == '0') t.pop_back(); reverse(t.begin(), t.end()); return t; } string to_bin(long long x) { if(x == 0) return ""; else { string s = to_bin(x / 2); s.push_back(char('0' + x % 2)); return s; } } int main() { long long x, y; cin >> x >> y; set<string> used; queue<string> q; q.push(to_bin(x)); used.insert(to_bin(x)); while(!q.empty()) { string k = q.front(); q.pop(); if(k.size() > 100) continue; for(int i = 0; i < 2; i++) { string k2 = go(k + string(1, char('0' + i))); if(!used.count(k2)) { used.insert(k2); q.push(k2); } } } if(used.count(to_bin(y))) cout << "YES\n"; else cout << "NO\n"; }