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
1362
B
Johnny and His Hobbies
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set $S$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a \textbf{positive} integer $k$ and replace each element $s$ of the set $S$ with $s \oplus k$ ($\oplus$ denotes the exclusive or operation). Help him choose such $k$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $\{1, 2, 3\}$ equals to set $\{2, 1, 3\}$. Formally, find the smallest positive integer $k$ such that $\{s \oplus k | s \in S\} = S$ or report that there is no such number. For example, if $S = \{1, 3, 4\}$ and $k = 2$, new set will be equal to $\{3, 1, 6\}$. If $S = \{0, 1, 2, 3\}$ and $k = 1$, after playing set will stay the same.
Consider $i$-th least significant bit ($0$ indexed). If it is set in $k$, but not in $s$, it will be set in $k \oplus s$. Hence $k \oplus s \geq 2^i$. Consider such minimal positive integer $m$, that $2^m > s$ holds for all $s \in S$. $k$ cannot have the $i$-th bit set for any $i \geq m$. From this follows that $k < 2^m$. So there are only $2^m$ feasible choices of $k$. We can verify if a number satisfies the condition from the statement in $\mathcal{O} \left(n \right)$ operations. This gives us a solution with complexity $\mathcal{O} \left(n \cdot 2^m \right)$. Note that in all tests $m$ is at most $10$. There is also another solution possible. It uses the observation that if $k$ satisfies the required conditions, then for every $s \in S$ there exists such $t \in S$ ($t \neq s$) , that $t \oplus s = k$. This gives us $n-1$ feasible choices of $k$ and thus the complexity of this solution is $\mathcal{O} \left( n^2 \right)$.
[ "bitmasks", "brute force" ]
1,200
//O(n * maxA) solution #include <bits/stdc++.h> using namespace std; const int N = 1025; int n; int in[N]; bool is[N]; bool check(int k){ for(int i = 1; i <= n; ++i) if(!is[in[i] ^ k]) return false; return true; } void solve(){ for(int i = 0; i < N; ++i) is[i] = false; scanf("%d", &n); for(int i = 1; i <= n; ++i){ scanf("%d", &in[i]); is[in[i]] = true; } for(int k = 1; k < 1024; ++k) if(check(k)){ printf("%d\n", k); return; } puts("-1"); } int main(){ int cases; scanf("%d", &cases); while(cases--) solve(); return 0; }
1362
C
Johnny and Another Rating Drop
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills. The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $5 = 101_2$ and $14 = 1110_2$ equals to $3$, since $0101$ and $1110$ differ in $3$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants. Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of \textbf{consecutive} integers from $0$ to $n$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.
Let us start by calculating the result for $n = 2^k$. It can be quickly done by calculating the results for each bit separately and summing these up. For $i$-th bit, the result is equal to $\frac{2^k}{2^{i}}$ as this bit is different in $d-1$ and $d$ iff $d$ is a multiple of $2^i$. Summing these up we get that the result for $n = 2^k$ is equal to $2^{k + 1} - 1 = 2n - 1$. How to compute the answer for arbitrary $n$? Let us denote $b_1 > b_2 > \ldots > b_k$ as set bits in the binary representation of $n$. I claim that the answer is equal to the sum of answers for $2^{b_1}, 2^{b_2}, \ldots, 2^{b_k}$. Why? We can compute results for intervals $[0, 2^{b_1}], [2^{b_1}, 2^{b_1} + 2^{b_2}], \ldots, [n - 2^{b_k}, n]$. We can notice that the result for interval $[s, s + 2^i]$, where $s$ is a multiple of $2^i$, is equal to the answer for $[0, 2^i]$ so we can just compute the results for intervals $[0, 2^{b_1}], [0, 2^{b_2}], \ldots, [0, 2^{b_k}]$! This allows us to compute the answer for arbitrary $n$ in $\mathcal{O}(\log n)$ - just iterate over all bits $b$ and add $2^{b + 1} - 1$ if $b$ is set. Equivalently we can just write down $2n - \texttt{#bits set}$ as the answer. Final complexity is $\mathcal{O}(t \log n)$.
[ "bitmasks", "greedy", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long LL; void solve(){ LL a; scanf("%lld", &a); LL ans = 0; for(int i = 0; i < 60; ++i) if(a & (1LL << i)) ans += (1LL << (i + 1)) - 1; printf("%lld\n", ans); } int main(){ int quest; scanf("%d", &quest); while(quest--) solve(); return 0; }
1363
A
Odd Selection
Shubham has an array $a$ of size $n$, and wants to select exactly $x$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so.
Key Idea: The sum of $x$ numbers can only be odd if we have an odd number of numbers which are odd. (An odd statement, indeed). Detailed Explanation: We first maintain two variables, num_odd and num_even, representing the number of odd and even numbers in the array, respectively. We then iterate over the number of odd numbers we can choose; which are $1,3,5,...$ upto min(num_odd,x), and see if num_even $\geq x - i$ where $i$ is the number of odd numbers we have chosen. Time complexity: $O(N)$
[ "brute force", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, x; int a[N], f[2]; int32_t main() { IOS; int t; cin >> t; while(t--) { f[0] = f[1] = 0; cin >> n >> x; for(int i = 1; i <= n; i++) { cin >> a[i]; f[a[i] % 2]++; } bool flag = 0; for(int i = 1; i <= f[1] && i <= x; i += 2) //Fix no of odd { int have = f[0], need = x - i; if(need <= f[0]) flag = 1; } if(flag) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
1363
B
Subsequence Hate
Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: - Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string. What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good. 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) characters.
Key Idea: There are two types of good strings: Those which start with a series of $1$'s followed by $0$'s (such as $1111100$) and those which start with a series of $0$'s followed by $1$'s (such as $00111$). Note that there are strings which do belong to both categories (such as $000$). Detailed Explanation: We will use the key idea to compute the minimum change required to achieve every possible string of each of the two types, and then take the minimum across them. First, let us compute the total number of $1$'s and $0$'s in the string, denoted by num_ones and num_zeros. Now, as we iterate through the string, let us also maintain done_ones and done_zeros, which denote the number of $1$'s and $0$'s encountered so far. Let us iterate through the string. When we are at position $i$ (indexed from $1$), we want to answer two questions: what is the cost for changing the string into $11..000$ (where number of $1$'s = $i$) and what is the cost for changing the string into $00..111$ (where number of $0$'s = $i$). Assuming that done_zeros and done_ones also consider the current index, the answer to the first question is done_zeros + num_ones - done_ones. This is because done_zeros $0$'s must be converted to $1$'s, and num_ones - done_ones $1$'s must be converted to $0$'s. Similarly, the answer for the second question is done_ones + num_zeros - done_zeros. The answer is the minimum over all such changes possible. Please do not forget to consider the all $1$'s and all $0$'s string in the above solution. Time Complexity: $O(N)$
[ "implementation", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int32_t main() { IOS; int t; cin >> t; while(t--) { string s; cin >> s; int suf0 = 0, suf1 = 0; for(auto &it:s) { suf0 += (it == '0'); suf1 += (it == '1'); } int ans = min(suf0, suf1); //Make whole string 0/1 int pref0 = 0, pref1 = 0; for(auto &it:s) { pref0 += (it == '0'), suf0 -= (it == '0'); pref1 += (it == '1'), suf1 -= (it == '1'); //Cost of making string 0*1* ans = min(ans, pref1 + suf0); //Cost of making string 1*0* ans = min(ans, pref0 + suf1); } cout << ans << endl; } return 0; }
1363
C
Game On Leaves
Ayush and Ashish play a game on an unrooted tree consisting of $n$ nodes numbered $1$ to $n$. Players make the following move in turns: - Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $1$. A tree is a connected undirected graph without cycles. There is a special node numbered $x$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.
Key Idea: The main idea of this problem is to think backwards. Instead of thinking about how the game will proceed, we think about how the penultimate state of the game will look like, etc. Also, we take care of the cases where the game will end immediately (i.e, when the special node is a leaf node). Detailed Explanation: First, let us take care of the cases where the game ends immediately. This only occurs when the special node $x$ is a leaf node, so all we must do is check that deg[$x$] = 1. Please note that $n = 1$ must be handled seperately here (just output Ayush). Now, in the case where $x$ is not a leaf node, the answer is as follows: Ashish wins if $n$ is odd, and Ayush wins if $n$ is even. I will provide a short sketch of the proof below. With the hint from the key idea, let us analyze this game backwards. (I will assume that $n>10$ for the sake of a clear explanation). When $x$ is removed from the game, it cannot be the only node remaining (because then the previous player could have also removed $x$, and thus he did not play optimally). Assume the structure of the game is something like the following WLOG at the last step (The tree attached to $x$ could be any tree): Consider also that Ayush won, and the last move was to remove $x$. Now, what could have been the state before this move? If Ashish had removed a node from the tree, then he did not play optimally - since he could have removed $x$! Thus, he must have removed something from $x$, which looks like the following: Considering this state, Ashish should not infact remove $6$, and instead remove something from the tree! Hence, the state that we assumed the game should look like at the end is impossible - and indeed, the tree attached to $x$ should only consist of only one node (we already proved that $x$ cannot be the only node remaining). Thus, all we have to do is find who's turn it will be when the structure of the tree is as follows: It is Ashish's turn if $n$ is odd, and Ayush's turn if $n$ is even. QED! Time complexity: $O(N)$
[ "games", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, x; int deg[N]; vector<int> g[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { memset(deg, 0, sizeof(deg)); cin >> n >> x; for(int i = 1; i <= n - 1; i++) { int u, v; cin >> u >> v; deg[u]++, deg[v]++; } if(deg[x] <= 1) cout << "Ayush" << endl; else { if(n % 2) cout << "Ashish" << endl; else cout << "Ayush" << endl; } } return 0; }
1363
D
Guess The Maximums
\textbf{This is an interactive problem.} Ayush devised a new scheme to set the password of his lock. The lock has $k$ slots where each slot can hold integers from $1$ to $n$. The password $P$ is a sequence of $k$ integers each in the range $[1, n]$, $i$-th element of which goes into the $i$-th slot of the lock. To set the password of his lock, Ayush comes up with an array $A$ of $n$ integers each in the range $[1, n]$ (not necessarily distinct). He then picks $k$ \textbf{non-empty mutually disjoint} subsets of indices $S_1, S_2, ..., S_k$ $(S_i \underset{i \neq j} \cap S_j = \emptyset)$ and sets his password as $P_i = \max\limits_{j \notin S_i} A[j]$. In other words, the $i$-th integer in the password is equal to the maximum over all elements of $A$ whose indices do not belong to $S_i$. You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. \textbf{You can ask no more than 12 queries}.
Key Idea: The maximum of the array is the password integer for all except atmost $1$ position. We find the subset (if the maximum is in a subset) in which the maximum exists using binary search, and then query the answer for this subset seperately. (For all the subsets, the answer is the maximum for the whole array). Detailed Explanation: I will be working with an example in this explanation; let the array be $a = [1,1,2,3,2,5,7,8,9,11,4]$, and array of length $11$, and let there be $10$ subsets, with first subset being $[1]$, second being $[2]$, etc (every index except $11$ is a subset). Thus, $a[1] = 1, a[3] = 2$, etc. First, let us query the maximum of the whole array using $1$ query. This gives $11$ as the output in our case. Now, we check if the maximum is present in the subsets. We do this in the following manner: we query the first half of the subsets. If the value returned here is not the maximum, then we search in the second half - else, we know that the maximum must be in the first half of subsets. Hence, we binary search in the first half itself. To proceed with our example, we query the maximum from subsets $1$ to $5$, which turns out to be $3$. Thus, $11$ must be present in subsets $6$ to $10$. Then we will query $6$ to $8$, which will return the value $8$ - thus, the maximum may be present in subset $9$, or $10$. Thus, we query subset $9$ and find that it does not contain the maximum. This step will require at most $10$ queries, and we will get a subset which (may or may not) contain the maximum element (remember, it is possible that the maximum element was not in any subset!) Thus, in our final query we ask about the maximum over all indices other than the canditate subset we found above. In our example, We query every index except those in subset $10$ using $1$ query, which gives us the answer as $9$. Hence, the password is $[11,11,11,11,11,11,11,11,11,9]$. Note: The bound of $12$ queries is tight. Time complexity: $O(N)$
[ "binary search", "implementation", "interactive", "math" ]
2,100
#include<bits/stdc++.h> using namespace std; #define vint vector<int> int interact(vint S){ cout << "? " << S.size() << ' '; for(int i : S) cout << i << ' '; cout << endl; int x; cin >> x; return x; } vint get_complement(vint v, int n){ vint ask, occur(n + 1); for(int i : v) occur[i] = 1; for(int i = 1; i <= n; i++) if(!occur[i]) ask.push_back(i); return ask; } int main(){ int tc; cin >> tc; while(tc--){ int n, k; cin >> n >> k; vector<vint> S(k); vint ans(k); for(int i = 0; i < k; i++){ int c; cin >> c; S[i].resize(c); for(int j = 0; j < c; j++) cin >> S[i][j]; } vint ask; for(int i = 1; i <= n; i++) ask.push_back(i); int max_element = interact(ask); //find subset with max element int st = 0, en = k - 1; while(st < en){ int mid = (st + en) / 2; ask.clear(); for(int i = 0; i <= mid; i++) for(int j : S[i]) ask.push_back(j); int x = interact(ask); if(x == max_element) en = mid; else st = mid + 1; } ask = get_complement(S[st], n); for(int i = 0; i < k; i++) if(i == st) ans[i] = interact(ask); else ans[i] = max_element; cout << "! "; for(int i : ans) cout << i << ' '; cout << endl; string correct; cin >> correct; } }
1363
E
Tree Shuffling
Ashish has a tree consisting of $n$ nodes numbered $1$ to $n$ rooted at node $1$. The $i$-th node in the tree has a cost $a_i$, and binary digit $b_i$ is written in it. He wants to have binary digit $c_i$ written in the $i$-th node in the end. To achieve this, he can perform the following operation any number of times: - Select any $k$ nodes from the subtree of any node $u$, and shuffle the digits in these nodes as he wishes, incurring a cost of $k \cdot a_u$. Here, he can choose $k$ ranging from $1$ to the size of the subtree of $u$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target. Help him find the minimum total cost he needs to spend so that after all the operations, every node $u$ has digit $c_u$ written in it, or determine that it is impossible.
Key Idea: Let the parent of node $i$ be $p$. If $a[i] \geq a[p]$, we can do the shuffling which was done at $i$, at $p$ instead. Thus, we can do the operation $a[i] = min(a[i],a[p])$. Detailed Explanation: Let us denote nodes that have $b_i = 1$ and $c_i = 0$ as type $1$, and those that have $b_i = 0$ and $c_i = 1$ as type $2$. Firstly, the answer is $-1$ if and only if the number of nodes of type $1$ and type $2$ are unequal. We also observe that only nodes of type $1$ and $2$ should be shuffled - it is unoptimal to shuffle those which already have $b[i] = c[i]$. Thus, we should try to exchange the values of type $1$ and type $2$ nodes. We use the key idea by going down from the root, and at every node $i$, setting $a[i] = min(a[i],a[p])$ where $p$ is the parent node of $i$ in the tree. Thus, the $a[i]$'s now follow a special structure: they are non-increasing from the root to the leaves! This paves the way for our greedy solution: we will go upwards from the leaves, and at each node $i$ interchange type $1$ and type $2$ nodes until we have no nodes in one of these types. Then, we pass on the remaining nodes to the parent to be shuffled. Time complexity: $O(N)$
[ "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, cost = 0; int arr[N], b[N], c[N]; vector<int> g[N]; pair<int, int> dfs(int u, int par, int mn) { pair<int, int> a = {0, 0}; if(b[u] != c[u]) { if(b[u]) a.first++; else a.second++; } for(auto &it:g[u]) { if(it == par) continue; pair<int, int> p = dfs(it, u, min(mn, arr[u])); a.first += p.first; a.second += p.second; } if(arr[u] < mn) { int take = min(a.first, a.second); cost += 2 * take * arr[u]; a.first -= take; a.second -= take; } return a; } int32_t main() { IOS; cin >> n; for(int i = 1; i <= n; i++) cin >> arr[i] >> b[i] >> c[i]; for(int i = 1; i <= n - 1; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } pair<int, int> ans = dfs(1, 0, 2e9); if(ans.first || ans.second) cout << -1; else cout << cost; return 0; }
1363
F
Rotating Substrings
You are given two strings $s$ and $t$, each of length $n$ and consisting of lowercase Latin alphabets. You want to make $s$ equal to $t$. You can perform the following operation on $s$ any number of times to achieve it — - Choose any substring of $s$ and rotate it clockwise once, that is, if the selected substring is $s[l,l+1...r]$, then it becomes $s[r,l,l + 1 ... r - 1]$. All the remaining characters of $s$ stay in their position. For example, on rotating the substring $[2,4]$ , string "abcde" becomes "adbce". 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. Find the minimum number of operations required to convert $s$ to $t$, or determine that it's impossible.
Key Idea: We note that a clockwise rotation is the same as taking a character at any position in the string, and inserting it anywhere to it's left. Thus, we process the strings from the end, build the suffixes and move towards the prefix. Detailed Explanation: The answer is $-1$ if both s and t do not have the same count of every character. Else, we can prove that it is always possible to convert s to t. Now, let us remove the largest common suffix of both s and t. Now, using the key idea, we consider a move as picking a character at any position in s and inserting it to it's left. So, let us just "pick up" characters, and use them in any order as we iterate through s. Our total cost is equal to the number of characters we picked overall. After removing common suffixes, suppose the last character of s is c. Since the last characters of s and t differ, we can pick up this c. Now, we want to make s[1,n-1] equal to t[1,n], given that we can insert c anywhere in s. Let us consider dp[i][j] (only for when j $\geq$ i, which means that we want to make s[1,i] = t[1,j] by inserting some characters that we have picked. What characters can we pick? We can pick the characters whose count in s[i+1,n] > t[j+1,n]. The base case is dp[0][i] = 0. Now, let us write the transitions for this dp solution. Suppose that t[j] = x. There are three possible transitions from dp[i][j]: If the count of x in s[i+1.n] is greater than it's count in t[j+1,n], then we can reach the state dp[i][j-1]. If s[i] = t[j], then we can reach the state dp[i-1][j-1]. We can pick up the character at position i (and insert it later) to reach dp[i-1][j] (with an additional cost of $1$). The final answer is dp[n][n]. Time complexity: $O(N^2)$
[ "dp", "strings" ]
2,600
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2005; int n; string s, t; int suf[26][N], suf2[26][N]; int cache[N][N]; int dp(int i, int j) { if(j == 0) return 0; int &ans = cache[i][j]; if(ans != -1) return ans; ans = 2e9; if(i > 0) { ans = 1 + dp(i - 1, j); if(s[i - 1] == t[j - 1]) ans = min(ans, dp(i - 1, j - 1)); } int ch = t[j - 1] - 'a'; if(suf[ch][i + 1] - suf2[ch][j + 1] > 0) ans = min(ans, dp(i, j - 1)); return ans; } int32_t main() { IOS; int tc; cin >> tc; while(tc--) { cin >> n >> s >> t; for(int i = 0; i <= n; i++) for(int j = 0; j <= n; j++) cache[i][j] = -1; for(int i = 0; i <= 25; i++) for(int j = 0; j <= n + 1; j++) suf[i][j] = suf2[i][j] = 0; for(int i = n; i >= 1; i--) { for(int j = 0; j < 26; j++) { suf[j][i] = suf[j][i + 1]; suf2[j][i] = suf2[j][i + 1]; } suf[s[i - 1] - 'a'][i]++; suf2[t[i - 1] - 'a'][i]++; } int ans = dp(n, n); if(ans > 1e9) ans = -1; cout << ans << endl; } return 0; }
1364
A
XXXXX
Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements \textbf{isn't} divisible by $x$, or determine that such subarray doesn't exist. An array $a$ is a subarray of an array $b$ if $a$ 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.
Let's start with the whole array. If every element in it is divisible by $x$, the answer is $-1$; if its sum isn't divisible by $x$, the answer is $n$. Otherwise, we must remove some elements. The key idea is that removing an element that is divisible by $x$ doesn't do us any benefits, but once we remove an element that isn't, the sum won't be divisible by $x$. So let the first non-multiple of $x$ be at index $l$, and the last one be at index $r$. We must either remove the prefix all the way up to $l$ or the suffix all the way up to $r$, and we'll clearly remove whichever shorter.
[ "brute force", "data structures", "number theory", "two pointers" ]
1,200
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n,x,sum=0,l=-1,r;\n\t\tscanf(\"%d%d\",&n,&x);\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tint a;\n\t\t\tscanf(\"%d\",&a);\n\t\t\tif (a%x)\n\t\t\t{\n\t\t\t\tif (l==-1)\n\t\t\t\tl=i;\n\t\t\t\tr=i;\n\t\t\t}\n\t\t\tsum+=a;\n\t\t}\n\t\tif (sum%x)\n\t\tprintf(\"%d\\n\",n);\n\t\telse if (l==-1)\n\t\tprintf(\"-1\\n\");\n\t\telse\n\t\tprintf(\"%d\\n\",n-min(l+1,n-r));\n\t}\n}"
1364
B
Most socially-distanced subsequence
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: - $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. - Among all such subsequences, choose the one whose length, $k$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them. A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements. A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
TL;DR the answer contains the first element, last element, and all the local minima and maxima, where a local minimum is an element less than its 2 adjacents, and a local maximum is an element greater than it 2 adjacents. Let's look at the expression in the problem for 3 numbers. If $a>b$ and $b>c$ or if $a<b$ and $b<c$, $|a-b|+|b-c|=|a-c|$, so it's never optimal to use $a$, $b$, and $c$ in a row because you can use just $a$ and $c$ and achieve a shorter subsequence. If you keep erasing your $b$'s from the original permutation, you'll end up with the first element, the last element, and the local minima and maxima. You can see that erasing any of them would decrease the expression, so this is the optimal answer.
[ "greedy", "two pointers" ]
1,300
"#include <bits/stdc++.h>\nusing namespace std;\nint p[100005];\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\",&n);\n\t\tfor (int i=1;i<=n;i++)\n\t\tscanf(\"%d\",&p[i]);\n\t\tvector<int> ans;\n\t\tfor (int i=1;i<=n;i++)\n\t\t{\n\t\t\tif (i==1 || i==n || (p[i-1]<p[i])!=(p[i]<p[i+1]))\n\t\t\tans.push_back(p[i]);\n\t\t}\n\t\tprintf(\"%d\\n\",ans.size());\n\t\tfor (int i:ans)\n\t\tprintf(\"%d \",i);\n\t\tprintf(\"\\n\");\n\t}\n}"
1364
C
Ehab and Prefix MEXs
Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that: - for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$. The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this.
The key observation is: if for some index $i$, $a_i \neq a_{i-1}$, then $b_i$ must be equal to $a_{i-1}$, since it's the only way to even change the prefix $MEX$. We can use this observation to fill some indices of $b$. Now, how do we fill the rest? Let's start by avoiding every element in $a$. Something special will happen if we avoid using any element from $a$ again. If we look at the first $i$ numbers in $b$, $a_i$ will indeed be excluded, so $MEX({b_1, b_2, \ldots, b_i}) \le a_i$. Now we need to make it as big as possible. How do we make it as big as possible? The logical thing to do is to fill the rest of $b$ with the numbers not in $a$ in increasing order. It turns out this construction always satisfies the conditions. Indeed, if we look at the first $i$ elements in $b$, every element less than $a_i$ will be present because $a_i \le i$ and we added the rest of the elements in increasing order.
[ "brute force", "constructive algorithms", "greedy" ]
1,600
"#include <bits/stdc++.h>\nusing namespace std;\nint a[100005],b[100005];\nbool ex[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<=n;i++)\n\tscanf(\"%d\",&a[i]);\n\tmemset(b,-1,sizeof(b));\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tif (a[i]!=a[i-1])\n\t\t{\n\t\t\tb[i]=a[i-1];\n\t\t\tex[b[i]]=1;\n\t\t}\n\t}\n\tex[a[n]]=1;\n\tint m=0;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\twhile (ex[m])\n\t\tm++;\n\t\tif (b[i]==-1)\n\t\t{\n\t\t\tb[i]=m;\n\t\t\tex[m]=1;\n\t\t}\n\t\tprintf(\"%d \",b[i]);\n\t}\n}"
1364
D
Ehab's Last Corollary
Given a connected undirected graph with $n$ vertices and an integer $k$, you have to either: - either find an independent set that has \textbf{exactly} $\lceil\frac{k}{2}\rceil$ vertices. - or find a \textbf{simple} cycle of length \textbf{at most} $k$. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
The common idea is: if the graph is a tree, you can easily find an independent set with size $\lceil\frac{n}{2}\rceil$ by bicoloring the vertices and taking the vertices from the more frequent color. Otherwise, the graph is cyclic. Let's get a cycle that doesn't have any edges "cutting through it." In other words, it doesn't have any pair of non-adjacent vertices connected by an edge. If its length is at most $k$, print it. Otherwise, take every other vertex (take a vertex and leave a vertex) and you'll end up with a big enough independent set. How to find such cycle? Let's do a dfs in our graph. In the very first time we hit a node that has a back-edge, we take the back-edge that goes to the deepest possible node to close our cycle. This cycle can't have any edges crossing it because none of our node's ancestors has a back-edge (by definition.) Let's get any cycle in the graph. Now, let's iterate over the edges that don't belong to the cycle. Whenever we meet one that "crosses the cycle," we use it to cut the cycle into 2 cycles with smaller length and keep any of them. When we finish, we'd have our desired cycle.
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation", "trees" ]
2,100
"#include <bits/stdc++.h>\nusing namespace std;\nint pos[100005];\nbool ex[100005];\nvector<int> v[100005],col[100005],s;\nvector<pair<int,int> > e;\ndeque<int> cyc;\nvoid dfs(int node)\n{\n\tpos[node]=s.size();\n\tcol[pos[node]%2].push_back(node);\n\ts.push_back(node);\n\tfor (int u:v[node])\n\t{\n\t\tif (pos[u]==-1)\n\t\tdfs(u);\n\t\telse if (cyc.empty() && pos[node]-pos[u]>1)\n\t\t{\n\t\t\tfor (int i=pos[u];i<=pos[node];i++)\n\t\t\t{\n\t\t\t\tcyc.push_back(s[i]);\n\t\t\t\tex[s[i]]=1;\n\t\t\t}\n\t\t}\n\t}\n\ts.pop_back();\n}\nint main()\n{\n\tint n,m,k;\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\twhile (m--)\n\t{\n\t\tint a,b;\n\t\tscanf(\"%d%d\",&a,&b);\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t\te.push_back({a,b});\n\t}\n\tmemset(pos,-1,sizeof(pos));\n\tdfs(1);\n\tif (cyc.empty())\n\t{\n\t\tif (col[0].size()<col[1].size())\n\t\tswap(col[0],col[1]);\n\t\tprintf(\"1\\n\");\n\t\tfor (int i=0;i<(k+1)/2;i++)\n\t\tprintf(\"%d \",col[0][i]);\n\t}\n\telse\n\t{\n\t\tfor (auto p:e)\n\t\t{\n\t\t\tif (ex[p.first] && ex[p.second] && abs(pos[p.first]-pos[p.second])!=1)\n\t\t\t{\n\t\t\t\twhile (cyc.front()!=p.first && cyc.front()!=p.second)\n\t\t\t\t{\n\t\t\t\t\tex[cyc.front()]=0;\n\t\t\t\t\tcyc.pop_front();\n\t\t\t\t}\n\t\t\t\twhile (cyc.back()!=p.first && cyc.back()!=p.second)\n\t\t\t\t{\n\t\t\t\t\tex[cyc.back()]=0;\n\t\t\t\t\tcyc.pop_back();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (cyc.size()<=k)\n\t\t{\n\t\t\tprintf(\"2\\n%d\\n\",cyc.size());\n\t\t\tfor (int i:cyc)\n\t\t\tprintf(\"%d \",i);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"1\\n\");\n\t\t\tfor (int i=0;i<(k+1)/2;i++)\n\t\t\tprintf(\"%d \",cyc[2*i]);\n\t\t}\n\t}\n}"
1364
E
X-OR
\textbf{This is an interactive problem!} Ehab has a hidden permutation $p$ of length $n$ consisting of the elements from $0$ to $n-1$. You, for some reason, want to figure out the permutation. To do that, you can give Ehab $2$ \textbf{different} indices $i$ and $j$, and he'll reply with $(p_i|p_j)$ where $|$ is the bitwise-or operation. Ehab has just enough free time to answer $4269$ questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will \textbf{not} change it depending on your queries. Can you guess the permutation?
The common idea is: if we find the index that contains $0$, we can query it with every element in $p$ and finish in $n$ queries (if you didn't do that, pleaaase share your solution.) How to get this index? Let's try to make a magic function that takes an index $i$ and tells us $p_i$. Assume you have an array $z$ such that $z_j$ is some index in the permutation that has a $0$ in the $j^{th}$ bit. Building our magic function with it turns out to be very easy. We'll just return $query(i,z_0)$&$query(i,z_1)$&$\ldots$&$query(i,z_{10})$. Why does that work? If $p_i$ has a $1$ in the $j^{th}$ bit, this expression will also have a $1$ because $p_i$ will make every single clause have a $1$. If it has a $0$, $query(i,z_j)$ will also have a $0$, making the whole expression have a $0$! But how do we find $z$? This turns out to be very easy. We'll query random pairs of indices, see where the result has a $0$, and update $z$. We stop once we fill every index in $z$. This works quickly because for any bit, at least half the numbers from $0$ to $n-1$ will have a $0$. Now we already have an $nlog(n)$ solution (call our magic function with every index,) but how to make less calls? Let's carry an index $idx$ that's supposed to have the index of $0$ in the end, and let $p_{idx}$ be stored in $val$. Initially, $idx$ is $1$ and $val$ could be found with our magic function. Now, let's iterate over the permutation. We'll query the current index, $i$, with $idx$. If the result isn't a subset of $val$, $p_i$ can't be $0$, so let's throw it in the trash. Otherwise, we'll make $idx$ equal to $i$ and use our magic function to update $val$. In my analysis, I'll use $c$ to denote something that's clearly small but needs big math to analyze it, so it's better to omit these analysis (or something that I can't analyze nervous chuckles.) Since every time $val$ is replaced with a subset of it, we only call our magic function at most $log(n)$ times, so the number of queries is at most $2n+log^2(n)+c$. The cool thing about this solution is that it barely relies on randomness, so even if you run it for a million test cases, it would still pass. In fact, try to make it deterministic with $\frac{n}{2}$ more queries. There's a nice speed-up, but it relies much more on randomness: ask your indices in a random order, and make an itsy bitsy edit in the magic function: if $val$ has a $0$ in the $j^{th}$ bit, you don't really need to query $i$ with $z_j$. You can set the $j^{th}$ bit in the result to $0$ right away because $p_i$ is a subset of $val$. That way, it doesn't always do $log(n)$ queries; it does however many ones $val$ has queries. This actually improves the solution to $2n+2log(n)+c$ on average! The intuition is: you start with a random number that has $\frac{log(n)}{2}$ ones in it (on average,) and every time you face a subset of it, the number of ones is expected to be halved, so the number of queries is around $log(n)+\frac{log(n)}{2}+\frac{log(n)}{4}+\ldots<2log(n)$. I'll describe a way to start with $n$ candidates to be $0$ and end up with $\sqrt{n}$ candidates. Let's query random pairs until we find a pair whose bitwise-or has at most $\frac{log(n)}{2}$ bits. Take one of the 2 indices in the pair (let's call it $i$) and query it with every candidate you have, and take the bitwise-and of the results. That will give you $p_i$. Now, let's make the numbers whose query result with $i$ is $p_i$ (hence, a subset of $p_i$) our new candidates. Since $i$ has at most $\frac{log(n)}{2}$ ones, the number of its subsets is $\sqrt{n}$, and we have our desired result! Now, to find the index of $0$, we'll just do this recursively until we have 2 candidates. We'll keep querying them with random indices until the results differ. The one giving a smaller result is our $0$. This solution does $2n+\sqrt{n}+\sqrt{\sqrt{n}}+\ldots+c$ queries. You may think this is much worse than the first solution, but apparently $\sqrt{n}$ is smaller than $log^2(n)$ for small $n$. And by small, I mean ~$10^5$. Thanks, Mohammad_Yasser for this solution. Assume you have 2 candidates for $0$ called $a$ and $b$ such that one of them is the index of $0$ at the end of our algorithm, and we always know $(p_a|p_b)$. Let's iterate over our indices in a random order and try to update $a$ and $b$. Assume the current index is $c$. Let's query to get $(p_b|p_c)$. We have 3 cases: If $(p_a|p_b)<(p_b|p_c)$, $p_c$ can't be $0$, so we'll throw it away. If $(p_a|p_b)>(p_b|p_c)$, $p_a$ can't be $0$, so we'll throw it away and change $a$ to be $c$. Otherwise, $p_b$ can't be $0$ because that would imply $p_a=p_c$ (recall that $p$ is a permutation.) So we can throw it away and change $b$ to be $c$. But notice that we now don't know $(p_a|p_b)$, so we're gonna have to make one more query, since we need to keep track of it. After we're done, we can narrow our 2 candidates down to 1 with the same way described in the previous solution.
[ "bitmasks", "constructive algorithms", "divide and conquer", "interactive", "probabilities" ]
2,700
"#include <bits/stdc++.h>\nusing namespace std;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint p[(1<<11)+5];\nint query(int i,int j)\n{\n\tprintf(\"? %d %d\\n\",i,j);\n\tfflush(stdout);\n\tint ans;\n\tscanf(\"%d\",&ans);\n\tassert(ans!=-1);\n\treturn ans;\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tvector<int> qp;\n\tfor (int i=1;i<=n;i++)\n\tqp.push_back(i);\n\tshuffle(qp.begin(),qp.end(),rng);\n\tint a=qp[0],b=qp[1],val=query(a,b);\n\tfor (int i=2;i<n;i++)\n\t{\n\t\tint tmp=query(b,qp[i]);\n\t\tif (tmp<val)\n\t\t{\n\t\t\ta=qp[i];\n\t\t\tval=tmp;\n\t\t}\n\t\telse if (tmp==val)\n\t\t{\n\t\t\tb=qp[i];\n\t\t\tval=query(a,qp[i]);\n\t\t}\n\t}\n\tint idx;\n\twhile (1)\n\t{\n\t\tint i=uniform_int_distribution<int>(1,n)(rng);\n\t\tif (i==a || i==b)\n\t\tcontinue;\n\t\tint t1=query(i,a),t2=query(i,b);\n\t\tif (t1!=t2)\n\t\t{\n\t\t\tidx=(t1<t2? a:b);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tif (i!=idx)\n\t\tp[i]=query(i,idx);\n\t}\n\tprintf(\"!\");\n\tfor (int i=1;i<=n;i++)\n\tprintf(\" %d\",p[i]);\n\tprintf(\"\\n\");\n\tfflush(stdout);\n}"
1365
A
Matrix Game
Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends. If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.
Key Idea: Vivek and Ashish can never claim cells in rows and columns which already have at least one cell claimed. So we need to look at the parity of minimum of the number of rows and columns which have no cells claimed initially. Solution: Let $a$ be the number of rows which do not have any cell claimed in them initially and similarly $b$ be the number of columns which do not have any cell claimed initially. Each time a player makes a move both $a$ and $b$ decrease by $1$, since they only claim cells in rows and columns with no claimed cells. If either one of $a$ or $b$ becomes $0$, the player whose turn comes next loses the game. Since both $a$ and $b$ decrease by $1$ after each move, $\min(a, b)$ becomes $0$ first. So, if $\min(a, b)$ is odd, Ashish wins the game otherwise Vivek wins. Time complexity: $O(n \cdot m)$
[ "games", "greedy", "implementation" ]
1,100
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 51; int n, m; int a[N][N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n >> m; set< int > r, c; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> a[i][j]; if(a[i][j] == 1) r.insert(i), c.insert(j); } } int mn = min(n — r.size(), m — c.size()); if(mn % 2) cout << "Ashish" << endl; else cout << "Vivek" << endl; } return 0; }
1365
B
Trouble Sort
Ashish has $n$ elements arranged in a line. These elements are represented by two integers $a_i$ — the value of the element and $b_i$ — the type of the element (there are only two possible types: $0$ and $1$). He wants to sort the elements in non-decreasing values of $a_i$. He can perform the following operation any number of times: - Select any two elements $i$ and $j$ such that $b_i \ne b_j$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $a_i$ after performing any number of operations.
Key Idea: If there is at least one element of type $0$ and at least one element of type $1$, we can always sort the array. Solution: If all the elements are of the same type, we cannot swap any two elements. So, in this case, we just need to check if given elements are already in sorted order. Otherwise, there is at least one element of type $0$ and at least one element of type $1$. In this case, it is possible to swap any two elements! We can swap elements of different types using only one operation. Suppose we want to swap two elements $a$ and $b$ of the same type. We can do it in $3$ operations. Let $c$ be an element of the type different from $a$ and $b$. We can first swap $a$ and $c$, then swap $b$ and $c$ and then swap $a$ and $c$ again. In doing so, $c$ remains at its initial position and $a$, $b$ are swapped. This is exactly how we swap two integers using a temporary variable. Since we can swap any two elements, it is always possible to sort the array in this case. Time complexity: $O(n)$
[ "constructive algorithms", "implementation" ]
1,300
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e3 + 5; int n; int a[N], b[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; bool sorted = 1, have0 = 0, have1 = 0; for(int i = 1; i <= n; i++) { cin >> a[i]; if(i >= 2 && a[i] < a[i - 1]) sorted = 0; } for(int i = 1; i <= n; i++) { cin >> b[i]; if(!b[i]) have0 = 1; else have1 = 1; } if(have0 && have1) cout << "Yes" << endl; else if(sorted) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
1365
C
Rotation Matching
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $n$. Let's call them $a$ and $b$. Note that a permutation of $n$ elements is a sequence of numbers $a_1, a_2, \ldots, a_n$, in which every number from $1$ to $n$ appears exactly once. The message can be decoded by an arrangement of sequence $a$ and $b$, such that the number of matching pairs of elements between them is maximum. A pair of elements $a_i$ and $b_j$ is said to match if: - $i = j$, that is, they are at the same index. - $a_i = b_j$ His two disciples are allowed to perform the following operation any number of times: - choose a number $k$ and cyclically shift one of the permutations to the left or right $k$ times. A single cyclic shift to the left on any permutation $c$ is an operation that sets $c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $c$ is an operation that sets $c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$ simultaneously. Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.
Key Idea: We only need to perform shifts on one of the arrays. Moreover, all the shifts can be of the same type (right or left)! Solution: First of all, a left cyclic shift is the same as $n - 1$ right cyclic shifts and vice versa. So we only need to perform shifts of one type, say right. Moreover, a right cyclic shift of $b$ is the same as performing a left cyclic shift on $a$ and vice versa. So we don't need to perform any shifts on $b$. Now the problem reduces to finding the maximum number of matching pairs over all right cyclic shifts of $a$. Since $n$ right cyclic shifts on $a$ results in $a$ again, there are only $n - 1$ right cyclic shifts possible. Since both arrays are a permutation, each element in $a$ would match with its corresponding equal element in $b$ only for one of the shifts. For example, if $a$ is $\{{2, 3, 1\}}$ and $b$ is $\{{3, 1, 2\}}$, the number $3$ in $a$ would match with the number $3$ in $b$ only if one right cyclic shift is performed. So for each element in $a$ we can find the number of right cyclic shifts after which it would match with its corresponding equal element in $b$. If $a_i$ = $b_j$, then $a_i$ would match with $b_j$ after $k = j - i$ right cyclic shifts. If $j - i \lt 0$, then $a_i$ would with $b_j$ after $n - j + i$ shifts. Now for each shift, we can find the number of matching pairs and take the maximum. Time complexity: $O(n)$ or $O(n \cdot log(n))$ if you use a map.
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
1,400
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n; int a[N], b[N], pos[N]; map< int, int > offset; int32_t main() { IOS; cin >> n; for(int i = 1; i <= n; i++) { cin >> a[i]; pos[a[i]] = i; } for(int i = 1; i <= n; i++) cin >> b[i]; for(int i = 1; i <= n; i++) { int cur = pos[b[i]] - i; if(cur < 0) cur += n; offset[cur]++; } int ans = 0; for(auto &it:offset) ans = max(ans, it.second); cout << ans; return 0; }
1365
D
Solve The Maze
Vivek has encountered a problem. He has a maze that can be represented as an $n \times m$ grid. Each of the grid cells may represent the following: - Empty — '.' - Wall — '#' - Good person  — 'G' - Bad person — 'B' The only escape from the maze is at cell $(n, m)$. A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' \textbf{cannot be blocked} and \textbf{can be travelled through}. Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions. \textbf{It is guaranteed that the cell $(n,m)$ is empty.} Vivek can also block this cell.
Key Idea: We can block all empty neighbouring cells of bad people and then check if all good people can escape and no bad people are able to escape. Solution: Consider all the neighbouring cells of bad people. There shouldn't be any path from these cells to the cell $(n, m)$. If there is a path from any such cell, the bad person adjacent to that cell can also then reach the cell $(n, m)$. So, if any good and bad people are in adjacent cells, the answer is "No". Based on this idea, we can block any empty cell neighbouring a bad person. Suppose there is another solution in which a cell $(i, j)$ neighbouring a bad person does not need to be blocked. There still won't be any path from $(i, j)$ to $(n, m)$ in that solution. So we can block $(i, j)$ in that solution too without affecting the solution itself. It is sufficient to block only the empty neighbouring cells of bad people and check the required conditions, which can be done using a bfs on the grid. Proof: We will assume there are no adjacent good and bad people since in that case, the answer is "No". There are three cases: A bad person is adjacent to the cell $(n, m)$. In this case, the cell $(n, m)$ must be blocked. Now no one will be able to escape. If there is at least one good person present, the answer is "No". If after blocking the neighbouring cells of bad people, there is some good person who is not able to escape, then the answer is again "No". Otherwise, the answer is always "Yes". Suppose there is some path from a bad person at cell $(i, j)$ to the cell $(n, m)$. One of the neighbours of this person must be another bad person since the only other case is an adjacent good person (which is already covered above). Extending this, all the cells on the path from $(i, j)$ to $(n, m)$ must have bad people. This is not possible since in this case, there must be a bad person adjacent to $(n, m)$ and this case is already covered above. Time complexity: $O(n \cdot m)$
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "shortest paths" ]
1,700
#include using namespace std; #define int long long typedef int ll; typedef long double ld; const ll N = 55; char en = '\n'; ll inf = 1e16; ll mod = 1e9 + 7; ll power(ll x, ll n, ll mod) { ll res = 1; x %= mod; while (n) { if (n & 1) res = (res * x) % mod; x = (x * x) % mod; n >>= 1; } return res; } ll n, m; char arr[N][N]; ll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool valid(ll i, ll j) { return i >= 1 && i <= n && j >= 1 && j <= m; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t; cin >> t; while (t--) { cin >> n >> m; for (ll i = 1; i <= n; i++) { cin >> (arr[i] + 1); } for (ll i = 1; i <= n; i++) { for (ll j = 1; j <= m; j++) { if (arr[i][j] == 'B') { for (ll k = 0; k < 4; k++) { ll ni = i + dir[k][0]; ll nj = j + dir[k][1]; if (valid(ni, nj) && arr[ni][nj] == '.') arr[ni][nj] = '#'; } } } } queue> que; bool visited[n + 5][m + 5]; memset(visited, false, sizeof(visited)); if (arr[n][m] == '.') { que.push({n, m}); visited[n][m] = true; } while (!que.empty()) { pair curr = que.front(); que.pop(); for (ll k = 0; k < 4; k++) { ll ni = curr.first + dir[k][0]; ll nj = curr.second + dir[k][1]; if (valid(ni, nj) && !visited[ni][nj] && arr[ni][nj] != '#') { que.push({ni, nj}); visited[ni][nj] = true; } } } bool good = true; for (ll i = 1; i <= n; i++) { for (ll j = 1; j <= m; j++) { if ((arr[i][j] == 'G' && !visited[i][j]) or (arr[i][j] == 'B' && visited[i][j])) { good = false; break; } } } cout << (good ? "Yes" : "No") << en; } return 0; }
1365
E
Maximum Subsequence Value
Ridhiman challenged Ashish to find the maximum valued subsequence of an array $a$ of size $n$ consisting of positive integers. The value of a non-empty subsequence of $k$ elements of $a$ is defined as $\sum 2^i$ over all integers $i \ge 0$ such that at least $\max(1, k - 2)$ elements of the subsequence have the $i$-th bit set in their binary representation (value $x$ has the $i$-th bit set in its binary representation if $\lfloor \frac{x}{2^i} \rfloor \mod 2$ is equal to $1$). Recall that $b$ is a subsequence of $a$, if $b$ can be obtained by deleting some(possibly zero) elements from $a$. Help Ashish find the maximum value he can get by choosing some subsequence of $a$.
Key Idea: For subsets of size up to $3$, their value is the bitwise OR of all elements in it. For any subset $s$ of size greater than $3$, it turns out that if we pick any subset of $3$ elements within it, then its value is greater than or equal to the value of $s$! Solution: Let $k$ be the size of the chosen subset. For $k \le 3$, $\max(k - 2, 1)$ is equal to $1$. This implies that their value is equal to the bitwise OR of all the elements in it (since we need to add $2^i$ for all $i$ such that at least $1$ element in the subset has $i$-th bit set in its binary representation). Consider any subset $s$ of size $k \gt 3$. Let $i$ be any number such that the $i$-th bit is set in at least $k - 2$ elements of $s$. If we pick any $3$ elements of this subset, then by Pigeonhole principle the $i$-th bit would also be set in at least one of these elements! If this is not true then the there are $3$ elements in $s$ which do not have the $i$-th bit set, which is not possible. So for any subset $s$ of size greater than $3$, its value is less than or equal to the value of any subset consisting of $3$ elements from $s$. Hence, we only need to check all subsets of size up to $3$. Time complexity: $O(n^3)$
[ "brute force", "constructive algorithms" ]
1,900
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 505; int n; int a[N]; int32_t main() { IOS; cin >> n; for(int i = 1; i <= n; i++) cin >> a[i]; int ans = 0; for(int i = 1; i <= n; i++) for(int j = i; j <= n; j++) for(int k = j; k <= n; k++) ans = max(ans, (a[i] | a[j] | a[k])); cout << ans; return 0; }
1365
F
Swaps Again
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into array $b$, the input is said to be valid. Otherwise, it is invalid. An operation on array $a$ is: - select an integer $k$ $(1 \le k \le \lfloor\frac{n}{2}\rfloor)$ - swap the prefix of length $k$ with the suffix of length $k$ For example, if array $a$ initially is $\{1, 2, 3, 4, 5, 6\}$, after performing an operation with $k = 2$, it is transformed into $\{5, 6, 3, 4, 1, 2\}$. Given the set of test cases, help them determine if each one is valid or invalid.
Key Idea: If we consider the unordered pair of elements $\{{a_i, a_{n - i + 1}\}}$, then after any operation, the multiset of these pairs (irrespective of the ordering of elements within the pair) stays the same! Solution: First of all, if the multiset of numbers in $a$ and $b$ are not the same, the answer is "No". Moreover, if $n$ is odd, it is not possible to change the middle element of $a$, i.e., $a_{(n + 1) / 2}$. So when $n$ is odd and elements at the position $(n + 1) / 2$ do not match in $a$ and $b$, the answer is again "No". Suppose we pair up the elements at equal distance from the middle element in $a$ (if $n$ is even, the middle element does not exist but we can treat it as the one between positions $n / 2$ and $n / 2 + 1$). That is, we pair up $\{{a_i, a_{n - i + 1}\}}$ (their individual order within the pair doesn't matter). After any operation on $a$, the multiset of these pairs does not change! If we swap a prefix of length $l$ with the suffix of length $l$, then consider any element at position $i \le l$ before the swap. It's new position is $n - l + i$ and the element it was paired with, i.e. the element at position $n - i + 1$ goes to the position $l - i + 1$. $(n - l + i) + (l - i + 1) = n + 1$, so these two elements are still paired after the swap. For example, if $a$ is $[1, 4, 2, 3]$, then the pairs are $\{{1, 3\}}$ and $\{{2, 4\}}$ (their individual ordering in the pair doesn't matter). Suppose we first apply the operation on the prefix of length $1$ and then the prefix of length $2$. After the first operation, $a$ is $[3, 4, 2, 1]$ and after the second operation, $a$ is $[2, 1, 3, 4]$. Note that in both these arrays, the pairings are still the same, i.e., $\{{1, 3\}}$ and $\{{2, 4\}}$. We conclude that in any array resulting after some number of operations, these pairings do not change with respect to the initial array. It turns out that all such arrays with same pairings as the initial array can be formed by performing these operations! So we only need to check if the multiset of these pairs in $b$ is the same as the multiset of pairs in $a$. Proof: We will show that given any array $b$ such that the multiset of pairs in $b$ is the same as the multiset of pairs in $a$, then we can form $b$ from $a$ in atmost $\lfloor{\frac{3 n}{2}}\rfloor$ operations. We will start constructing the pairs in $b$ starting from $b_{n / 2}$ to $b_{1}$, i.e., we first bring elements $b_{n / 2}$ and $b_{n - n / 2 + 1}$ to their position in $a$ followed by $b_{n / 2 - 1}$ and so on. Note that if we bring the elements $b_{n / 2}$ and $b_{n - n / 2 + 1}$ to their respective positions in $a$ then we can delete them in both $a$ and $b$ and continue the construction. Suppose we currently want to bring elements $b_i$ and $b_{n - i + 1}$ $(i \le n/2)$ to their respective positions in $a$. If $b_i$ is at position $j$ in $a$, then $b_{n - i + 1}$ must be at the position $n - j + 1$. There are three cases: If $j = n$, then we can swap the prefix and suffix of length $i$ in $a$ to achieve this. Otherwise if $j = 1$, then we can first swap prefix and suffix of length $1$ and then swap prefix and suffix of length $i$. Else we can swap prefix and suffix of length $j$ in $a$ and proceed to steps $1$ and $2$. In atmost $3$ steps, we can bring each pair in $a$ to its required position in $b$. So we need atmost $\lfloor{\frac{3 n}{2}}\rfloor$ operations overall. Time complexity: $O(n \cdot \log{n})$
[ "constructive algorithms", "implementation", "sortings" ]
2,100
#include using namespace std; int main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int tc; cin >> tc; while(tc--){ int n; cin >> n; map< pair < int, int >, int > pairs; vector< int > a(n), b(n); bool possible = 1; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) cin >> b[i]; if(n % 2 == 1 && a[n / 2] != b[n / 2]) possible = 0; for(int i = 0; i < n / 2; i++){ pair< int, int > p = {min(a[i], a[n — 1 — i]), max(a[i], a[n — 1 — i])}; pairs[p]++; } for(int i = 0; i < n / 2; i++){ pair< int, int > p = {min(b[i], b[n — 1 — i]), max(b[i], b[n — 1 — i])}; if(pairs[p] <= 0) possible = 0; pairs[p]--; } if(possible) cout << "Yes" << endl; else cout << "No" << endl; } }
1365
G
Secure Password
\textbf{This is an interactive problem.} Ayush devised yet another scheme to set the password of his lock. The lock has $n$ slots where each slot can hold any non-negative integer. The password $P$ is a sequence of $n$ integers, $i$-th element of which goes into the $i$-th slot of the lock. To set the password, Ayush comes up with an array $A$ of $n$ integers each in the range $[0, 2^{63}-1]$. He then sets the $i$-th element of $P$ as the bitwise OR of all integers in the array except $A_i$. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the \textbf{bitwise OR} all elements of the array with index in this subset. \textbf{You can ask no more than 13 queries}.
Key Idea: Unlike the last version of the problem, this is not doable using a binary search. Solution using more queries: It is possible to solve the problem using $2\cdot \log{n}$ queries in the following way: For each $i$, we ask the bitwise OR of all numbers at indices which have the $i$-th bit set in their binary representation. We also ask the bitwise OR of all numbers at indices which do not have the $i$-th bit set in their binary representation. Suppose we want to calculate the bitwise OR of all numbers except the $i$-th number. Let the bitwise OR be equal to $a$ (initialize $a= 0$). We iterate on all indices $j$ from $1$ to $n$ (except $i$). If $j$ is a submask of $i$, that is $j \wedge i = j$ (where $\wedge$ is the bitwise AND operator), then there must be some bit $k$ that is set in $i$ but not in $j$ (since $i \ne j$). In this case we replace $a$ by $a \vee x$ where $\vee$ is the bitwise OR operator and $x$ is the bitwise OR of numbers at indices that do no have the $k$-th bit set. Similarly, if $j$ is not a submask of $i$ then there must be some bit $k$ which is set in $j$ but not in $i$. In that case we use the bitwise OR of numbers at indices that have the $k$-th bit set. In doing so, we included the contribution of each element except $i$ at least once. Note that this works because taking the bitwise OR with the same number more than once does not affect the answer. For example, if $n=4$ and indices are number $0$ to $3$, then we need to ask $4$ queries: $\{{0, 2\}}$ (bit $0$ not set), $\{{1, 3\}}$ (bit $0$ set), $\{{0, 1\}}$ (bit $1$ not set), $\{{2, 3\}}$ (bit $1$ set). Solution: Note that in the suboptimal solution, we assigned a bitmask to each index (in that case bitmask for index $i$ was equal to $i$). What if we assign these masks in a different way? Suppose we are able to assign the masks in such a way that no two masks assigned to two indices are submasks of each other. In this case, we do not need to ask bitwise OR of indices which do not have the $i$-th bit set since for each pair of indices, there is a bit which is set in one but not in the other. For example, if $n = 4$, we can assign masks 1100, 1010, 1001 and 0110 (in binary representation). Now for each bit $i$, we will only query the indices which have the $i$-th bit set. In this case, for bit $0$ we ask $\{{3\}}$, for bit $1$ we ask $\{{2, 4\}}$, for bit $2$ we ask $\{{1, 4\}}$ and for bit $3$ we ask $\{{1, 2, 3\}}$. Let $x_0, x_1, x_2, x_3$ be bitwise OR of these four subsets respectively. Then the elements of the password are $x_0 \vee x_1$, $x_0 \vee x_2$, $x_1 \vee x_2$ and $x_0 \vee x_3$ respectively. What is the minimum number of bits we need to assign masks in such a way? We are given the bound of $13$ queries. There are $1716$ numbers upto $2^{13}$ which have $6$ bits set in their binary representation. Clearly no two of these numbers would be submaks of each other. So we can use them to assign the masks! It can be shown using Sperner's theorem that we need at least $13$ queries to assign submaks in the above manner. Time complexity: $O(2^q + n \cdot q)$ where $q$ is the number of queries asked.
[ "bitmasks", "combinatorics", "constructive algorithms", "interactive", "math" ]
2,800
#include using namespace std; #define ll long long #define vint vector< int > const int Q = 13; ll query(vint v){ cout << "? " << v.size() << ' '; for(ll i : v) cout << i + 1 << ' '; cout << endl; fflush(stdout); ll or_value; cin >> or_value; return or_value; } int main(){ int n; cin >> n; vector< vint > ask(Q); vint assign_mask(n); vector< ll > or_value(Q), answer(n); int assigned = 0; for(int i = 1; i < (1 << Q); i++){ if(__builtin_popcount(i) != Q / 2) continue; assign_mask[assigned] = i; for(int j = 0; j < Q; j++) if((i >> j & 1) == 0) ask[j].push_back(assigned); assigned++; if(assigned == n) break; } for(int i = 0; i < Q; i++) if(!ask[i].empty()) or_value[i] = query(ask[i]); for(int i = 0; i < n; i++) for(int j = 0; j < Q; j++) if(assign_mask[i] >> j & 1) answer[i] |= or_value[j]; cout << "! "; for(ll i : answer) cout << i << ' '; cout << endl; }
1366
A
Shovels and Swords
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $a$ sticks and $b$ diamonds?
There are three constraints on the number of emeralds: the number of emeralds can't be greater than $a$; the number of emeralds can't be greater than $b$; the number of emeralds can't be greater than $\frac{a+b}{3}$. So the answer is $\min(a, b, \frac{a+b}{3})$.
[ "binary search", "greedy", "math" ]
1,100
for _ in range(int(input())): l, r = map(int, input().split()) print(min(l, r, (l + r) // 3))
1366
B
Shuffle
You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$. You have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \le c, d \le r_i$, and swap $a_c$ and $a_d$. Calculate the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end.
Let's consider how the set of possible indices where the $1$ can be changes. Initially, only one index is correct - $x$. After performing an operation $l, r$ such that $x < l$ or $x > r$ this set does not change. But after performing an operation $l, r$ such that $l \le x \le r$ we should insert the elements $\{l, l+1, l+2, \dots, r-1, r\}$ into this set, if they are not present. Now consider how the set $\{L, L+1, L+2, \dots, R-1, R\}$ changes. If segments $[l, r]$ and $[L, R]$ do not share any indices, there are no changes - but if they do, the set turns into $\{ \min(l, L), \min(l, L)+1, \min(l, L)+2, \dots, \max(r, R)-1, \max(r, R) \}$. So the set of reachable indices is always a segment of numbers, and to process an operation, we should check whether the segment from operation intersects with the segment of indices we have - and if it is true, unite them.
[ "math", "two pointers" ]
1,300
for _ in range(int(input())): n, x, m = map(int, input().split()) l, r = x, x for _ in range(m): L, R = map(int, input().split()) if max(l, L) <= min(r, R): l = min(l, L) r = max(r, R) print(r - l + 1)
1366
C
Palindromic Paths
You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$. A chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $(x, y)$, then after the move it can be either $(x + 1, y)$ or $(x, y + 1)$). The chip cannot leave the matrix. Consider each path of the chip from $(1, 1)$ to $(n, m)$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on. Your goal is to change the values in the minimum number of cells so that \textbf{every} path is palindromic.
Let's group the cells by their distance from the starting point: the group $0$ consists of a single cell $(1, 1)$; the group $1$ consists of the cells $(1, 2)$ and $(2, 1)$, and so on. In total, there are $n + m - 1$ groups. Let's analyze the groups $k$ and $n + m - 2 - k$. There are two cases: if $k = 0$ or $n + m - 2 - k = 0$, then we are looking at the starting cell and the ending cell, and their contents should be equal; otherwise, suppose two cells $(x, y)$ and $(x + 1, y - 1)$ belong to the same group. We can easily prove that the contents of these two cells should be equal (for example, by analyzing two paths that go through cell $(x + 1, y)$ and coincide after this cell, but one goes to $(x + 1, y)$ from $(x, y)$, and another - from $(x + 1, y - 1)$) - and, using induction, we can prove that the contents of all cells in a group should be equal. And since the paths should be palindromic, the contents of the group $k$ should be equal to the contents of the group $n + m - 2 - k$. So, in each pair of groups, we should calculate the number of $1$'s and $0$'s, and choose which of them to change. Note that if $n + m$ is even, the central group has no pair, so it should not be modified.
[ "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<vector<int> > a(n, vector<int>(m)); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> a[i][j]; vector<vector<int> > cnt(n + m - 1, vector<int>(2)); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cnt[i + j][a[i][j]]++; int ans = 0; for(int i = 0; i <= n + m - 2; i++) { int j = n + m - 2 - i; if(i <= j) continue; ans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1]); } cout << ans << endl; } int main() { int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
1366
D
Two Divisors
You are given $n$ integers $a_1, a_2, \dots, a_n$. For each $a_i$ find its \textbf{two divisors} $d_1 > 1$ and $d_2 > 1$ such that $\gcd(d_1 + d_2, a_i) = 1$ (where $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$) or say that there is no such pair.
Firstly, for the fast factorization of given $a_i$, let's use Sieve of Eratosthenes: let's for each value $val \le 10^7$ calculate its minimum prime divisor $minDiv[val]$ in the same manner as the sieve do. Now we can factorize each $a_i$ in $O(\log{a_i})$ time by separating its prime divisors one by one using precalculated array $minDiv$. Suppose, we have a factorization $a_i = p_1^{s_1} p_2^{s_2} \cdot \ldots \cdot p_k^{s_k}$. If $k = 1$ then any divisor of $a_i$ is divisible by $p_1$ so do the sum of divisors. Obviously, the answer is $-1$ $-1$. Otherwise, we can divide all prime divisors $p_i$ into two non-empty groups $\{p_1, p_2, \dots, p_x\}$ and $\{p_{x + 1}, \dots, p_k\}$ and take $d_1 = p_1 \cdot p_2 \cdot \ldots \cdot p_x$ and $d_2 = p_{x + 1} \cdot \ldots \cdot p_k$. Any division is valid (proof is below), so, for example, we can take $d_1 = p_1$ and $d_2 = p_2 \cdot \ldots \cdot p_k$. Let's prove that if $d_1 = p_1 \cdot p_2 \cdot \ldots \cdot p_x$ and $d_2 = p_{x + 1} \cdot \ldots \cdot p_k$ then $\gcd(d_1 + d_2, a_i) = 1$. Let's look at any $p_i$. We can assume that $a_i \equiv 0 \mod p_i$ and (without loss of generality) $d_1 \equiv 0 \mod p_i$. But it means that $d_2 \not\equiv 0 \mod p_i$, then $d_1 + d_2 \equiv 0 + d_2 \equiv d_2 \not\equiv 0 \mod p_i$. In other words, there are no prime divisor of $a_i$ which divides $d_1 + d_2$, so the $\gcd(d_1 + d_2, a_i) = 1$. Time complexity is $O(A \log{\log{A}} + n \log{A})$ for the sieve and finding answers ($A \le 10^7$).
[ "constructive algorithms", "math", "number theory" ]
2,000
fun main() { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() } val minDiv = IntArray(1e7.toInt() + 2) { it } for (i in 2 until minDiv.size) { if (minDiv[i] != i) continue for (j in i until minDiv.size step i) minDiv[j] = minOf(minDiv[j], i) } fun getPrimeDivisors(v: Int): ArrayList<Int> { val ans = ArrayList<Int>() var curVal = v while (curVal != 1) { if (ans.isEmpty() || ans.last() != minDiv[curVal]) ans.add(minDiv[curVal]) curVal /= minDiv[curVal] } return ans } val d1 = IntArray(n) val d2 = IntArray(n) for (id in a.indices) { val list = getPrimeDivisors(a[id]) if (list.size < 2) { d1[id] = -1 d2[id] = -1 } else { d1[id] = list[0] list.removeAt(0) d2[id] = list.reduce { s, t -> s * t } } } println(d1.joinToString(" ")) println(d2.joinToString(" ")) }
1366
E
Two Arrays
You are given two arrays $a_1, a_2, \dots , a_n$ and $b_1, b_2, \dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$). You have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal to $b_i$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $a$ compose the first subarray, the next several elements of $a$ compose the second subarray, and so on. For example, if $a = [12, 10, 20, 20, 25, 30]$ and $b = [10, 20, 30]$ then there are two good partitions of array $a$: - $[12, 10, 20], [20, 25], [30]$; - $[12, 10], [20, 20, 25], [30]$. You have to calculate the number of ways to divide the array $a$. Since the number can be pretty large print it modulo 998244353.
At first, let's reverse arrays $a$ and $b$. Now array $b$ is sorted in descending order. Now let's find minimum index $x$ such that $a_x = b_1$. If there is no such index or if $\min\limits_{1 \le i \le x}a_i < b_1$ then the answer is $0$ (because minimum on any prefix of array $a$ will never be equal to $b_1$). Otherwise, let's find the minimum index $y > x$ such that $a_y = b_2$. If there is no such index or if $\min\limits_{x \le i \le y}a_i < b_2$ then the answer is $0$. Also let's find the minimum index $mid > x$ such that $a_{mid} < b_1$ (it can't be greater than $y$). The first subarray starts in position $1$ and ends in any position $x, x + 1, x + 2, \dots, mid - 1$ (because if it ends in position $mid$ or further, then the minimum in the first subarray is greater than $b_1$). So there are $mid - x$ ways to split subarrays $1$ and $2$. A similar approach can be used to calculate the number of ways to split the second and third subarrays and, so on. After all, you have to check that minimum in the last subarray is equal to $b_m$ (otherwise the answer is $0$).
[ "binary search", "brute force", "combinatorics", "constructive algorithms", "dp", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 200005; const int MOD = 998244353; int mul(int a, int b) { return (a * 1LL * b) % MOD; } int n, m; int a[N], b[N]; int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) scanf("%d", a + i); for (int i = 0; i < m; ++i) scanf("%d", b + i); reverse(a, a + n); reverse(b, b + m); a[n] = -1; int mn = a[0]; int pos = 0; while (pos < n && mn > b[0]) { ++pos; mn = min(mn, a[pos]); } if (pos == n || mn < b[0]) { puts("0"); return 0; } assert(mn == b[0]); int res = 1; int ib = 0; while (true) { assert(mn == b[ib]); if (ib == m - 1){ if(*min_element(a + pos, a + n) != b[ib]) { puts("0"); return 0; } break; } bool f = true; int npos = pos; while (npos < n && mn != b[ib + 1]) { ++npos; mn = min(mn, a[npos]); if (f && mn < b[ib]){ f = false; res = mul(res, npos - pos); } } if (npos == n || mn != b[ib + 1]) { puts("0"); return 0; } ++ib; pos = npos; } printf("%d\n", res); return 0; }
1366
F
Jog Around The Graph
You are given a simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges. A path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \dots, v_{k+1}$ such that for each $i$ $(1 \le i \le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also has vertex $v_1=v$. Note that edges and vertices are allowed to be included in the path multiple times. The weight of the path is the total weight of edges in it. For each $i$ from $1$ to $q$ consider a path from vertex $1$ of length $i$ of the maximum weight. What is the sum of weights of these $q$ paths? Answer can be quite large, so print it modulo $10^9+7$.
Let's observe what does the maximum weight of some fixed length path look like. Among the edges on that path the last one has the maximum weight. If it wasn't then the better total weight could be achieved by choosing a bigger weight edge earlier and going back and forth on it for the same number of steps. It actually helps us arrive to a conclusion that all optimal paths look like that: some simple path to an edge and then back and forth movement on it. Any simple path in the graph has its length at most $m$. Let's separate the queries into two parts. $k < m$ will be handled in a straightforward manner. Let $dp[v][k]$ be the maximum weight of a path that ends in $v$ and has exactly $k$ edges in it. That's pretty easy to calculate in $(n+m) \cdot m$. You can also think of this $dp$ as some kind of Ford-Bellman algorithm - let $d_v$ on the $k$-th step be the maximum weight of the path to $v$ of length $k$. Iterate over all edges and try to update $d_v$ and $d_u$ for each edge $(v, u)$ (that's what I do in my solution if you refer to it). Now for $k \ge m$. There was a very common assumption that after a bit more steps some edge will become the most optimal and will stay the most optimal until the end of time. However, that "a bit" cut-off is in fact too high to rely on (it must be somewhere around $n \cdot max_w$). So the best path of length exactly $m$ ending in each vertex $v$ is $dp[v][m]$. Let the maximum weight adjacent edge to vertex $v$ be $mx_v$. So the path of length $k$ will have weight $mx_v \cdot (k - m) + dp[v][m]$. Treat it like a line $kx + b$ with coefficients $mx_v$ and $dp[v][m]$. How do determine which line is the best for some $k$? Sure, experienced participants will immediately answer "convex hull". Build a lower envelope of the convex hull of these lines. If $q$ was a little smaller than we could query with binary search for each $k$, the same how convex hull is usually used. We have to examine the hull further. Each line in it becomes the best in some point, then stays the best for some interval and then never appears the best again. What are these line changing points? Well, it's just the intersection point of the adjacent lines in the hull. So having these points and the parameters of the line we can calculate its contribution to the answer with a sum of arithmetic progression formula. There were just $n$ lines in the hull so you can build the hull in any complexity, I think I saw up to $O(n^2 \log n)$ performances in the participants codes. There is a cool solution that involves some kind of Divide&Conquer on these lines. I personally thought of it in a sense of traversing a Li-Chao tree without actually building it. If anyone wants to explain this solution, feel free to do it in comments. Overall complexity: $O((n+m) \cdot m + n \log n)$.
[ "binary search", "dp", "geometry", "graphs" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const long long INF = 1e18; const int MOD = 1000'000'007; const int inv2 = (MOD + 1) / 2; struct edge{ int v, u, w; }; struct frac{ long long x, y; frac(long long a, long long b){ if (b < 0) a = -a, b = -b; x = a, y = b; } }; bool operator <=(const frac &a, const frac &b){ return a.x * b.y <= a.y * b.x; } struct line{ long long m, c; frac intersectX(const line &l) { return frac(c - l.c, l.m - m); } }; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int calc(int a1, int d, int n){ assert(n >= 0); return mul(mul(n, inv2), add(mul(2, a1), mul(add(n, -1), d))); } int main() { int n, m; long long q; scanf("%d%d%lld", &n, &m, &q); vector<edge> e(m); vector<int> hv(n); forn(i, m){ scanf("%d%d%d", &e[i].v, &e[i].u, &e[i].w); --e[i].v, --e[i].u; hv[e[i].v] = max(hv[e[i].v], e[i].w); hv[e[i].u] = max(hv[e[i].u], e[i].w); } int ans = 0; vector<long long> d(n, -INF), nd(n); d[0] = 0; forn(val, m){ long long mx = 0; forn(i, n) mx = max(mx, d[i]); if (val) ans = add(ans, mx % MOD); nd = d; forn(i, m){ nd[e[i].v] = max(nd[e[i].v], d[e[i].u] + e[i].w); nd[e[i].u] = max(nd[e[i].u], d[e[i].v] + e[i].w); } d = nd; } vector<line> fin; forn(i, n) fin.push_back({hv[i], d[i]}); sort(fin.begin(), fin.end(), [](const line &a, const line &b){ if (a.m != b.m) return a.m < b.m; return a.c > b.c; }); fin.resize(unique(fin.begin(), fin.end(), [](const line &a, const line &b){ return a.m == b.m; }) - fin.begin()); vector<line> ch; for (auto cur : fin){ while (ch.size() >= 2 && cur.intersectX(ch.back()) <= ch.back().intersectX(ch[int(ch.size()) - 2])) ch.pop_back(); ch.push_back(cur); } long long prv = 0; q -= m; forn(i, int(ch.size()) - 1){ frac f = ch[i].intersectX(ch[i + 1]); if (f.x < 0) continue; long long lst = min(q, f.x / f.y); if (lst < prv) continue; ans = add(ans, calc((ch[i].c + ch[i].m * prv) % MOD, ch[i].m % MOD, lst - prv + 1)); prv = lst + 1; } ans = add(ans, calc((ch.back().c + ch.back().m * prv) % MOD, ch.back().m % MOD, q - prv + 1)); printf("%d\n", ans); return 0; }
1366
G
Construct the String
Let's denote the function $f(s)$ that takes a string $s$ consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows: - let $r$ be an empty string; - process the characters of $s$ from left to right. For each character $c$, do the following: if $c$ is a lowercase Latin letter, append $c$ at the end of the string $r$; otherwise, delete the last character from $r$ (if $r$ is empty before deleting the last character — the function crashes); - return $r$ as the result of the function. You are given two strings $s$ and $t$. You have to delete the minimum possible number of characters from $s$ so that $f(s) = t$ (and the function does not crash). Note that you aren't allowed to insert new characters into $s$ or reorder the existing ones.
The core idea of the solution is the following dynamic programming: $dp_{i, j}$ is the minimum number of characters we have to delete if we considered a subsequence of $i$ first characters of $s$, and it maps to $j$ first characters of $t$. There are three obvious transitions in this dynamic programming: we can go from $dp_{i, j}$ to $dp_{i + 1, j}$ by skipping $s_i$; if $s_i = t_j$, we can go from $dp_{i, j}$ to $dp_{i + 1, j + 1}$; if $s_i$ is a dot, we can go from $dp_{i, j}$ to $dp_{i + 1, j - 1}$. Unfortunately, these transitions cannot fully handle the case when we want to put some character and then delete it (these transitions don't allow us to do it for any character, only for some specific ones in specific situations). To handle it, suppose we want to take the character $s_i$ and then delete it, and we model it as follows: there exists the fourth transition from $dp_{i,j}$ to $dp_{i+len_i, j}$ without deleting anything, where $len_i$ is the length of the shortest substring of $s$ starting from $i$ that becomes empty if we apply the function $f$ to it. This substring can be described as a regular bracket sequence, where opening brackets correspond to letters, and closing brackets - to dots. We can precalculate this substring for each $i$ in $O(n)$. Why is this transition enough? Suppose we don't want to take some letter from this shortest substring in the optimal answer; since it is the shortest substring meeting these constraints, the number of letters on each prefix of it (excluding the substring itself) is greater than the number of dots, so we can instead skip the first letter and try applying this transition from $dp_{i + 1, j}$, so this case is handled. And skipping any dots from this shortest substring is also suboptimal since we have to get rid of the character $s_i$.
[ "data structures", "dp", "strings" ]
2,700
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #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) const int INF = 1e9; const int N = 10010; int n, m; string s, t; int dp[N][N]; int nxt[N]; int main() { cin >> s >> t; n = sz(s), m = sz(t); forn(i, n) if (s[i] != '.') { int bal = 0; nxt[i] = -1; fore(j, i, n) { if (s[j] == '.') --bal; else ++bal; if (bal == 0) { nxt[i] = j; break; } } } forn(i, n + 1) forn(j, m + 1) dp[i][j] = INF; dp[0][0] = 0; forn(i, n) forn(j, m + 1) { dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1); if (j < m && s[i] == t[j]) dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]); if (s[i] != '.' && nxt[i] != -1) dp[nxt[i] + 1][j] = min(dp[nxt[i] + 1][j], dp[i][j]); } cout << dp[n][m] << endl; }
1367
A
Short Substrings
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string $a$ consisting of lowercase English letters. The string $a$ has a length of $2$ or more characters. Then, from string $a$ he builds a new string $b$ and offers Alice the string $b$ so that she can guess the string $a$. Bob builds $b$ from $a$ as follows: he writes all the substrings of length $2$ of the string $a$ in the order from left to right, and then joins them in the same order into the string $b$. For example, if Bob came up with the string $a$="abac", then all the substrings of length $2$ of the string $a$ are: "ab", "ba", "ac". Therefore, the string $b$="abbaac". You are given the string $b$. Help Alice to guess the string $a$ that Bob came up with. It is guaranteed that $b$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.
Note that the first two characters of $a$ match the first two characters of $b$. The third character of the string $b$ again matches the second character of $a$ (since it is the first character in the second substring, which contains the second and the third character of $a$). The fourth character $b$ matches with the third character of $a$. It is easy to notice that such a pattern continues further. That is, the string $a$ consists of the first character $b$ and all characters at even positions in $b$.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int test = 1; test <= t; test++) { string b; cin >> b; string a = b.substr(0, 2); for (int i = 3; i < b.size(); i += 2) { a += b[i]; } cout << a << endl; } return 0; }
1367
B
Even Array
You are given an array $a[0 \ldots n-1]$ of length $n$ which consists of non-negative integers. \textbf{Note that array indices start from zero.} An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $i$ ($0 \le i \le n - 1$) the equality $i \bmod 2 = a[i] \bmod 2$ holds, where $x \bmod 2$ is the remainder of dividing $x$ by 2. For example, the arrays [$0, 5, 2, 1$] and [$0, 17, 0, 3$] are good, and the array [$2, 4, 6, 7$] is bad, because for $i=1$, the parities of $i$ and $a[i]$ are different: $i \bmod 2 = 1 \bmod 2 = 1$, but $a[i] \bmod 2 = 4 \bmod 2 = 0$. In one move, you can take \textbf{any} two elements of the array and swap them (these elements are not necessarily adjacent). Find the minimum number of moves in which you can make the array $a$ good, or say that this is not possible.
We split all the positions in which the parity of the index does not match with the parity of the element into two arrays. If there is an odd number in the even index, add this index to the $e$ array. Otherwise, if there is an even number in the odd index, add this index to the $o$ array. Note that if the sizes of the $o$ and $e$ arrays are not equal, then there is no answer. Otherwise, the array $a$ can be made good by doing exactly $|o|$ operations by simply swapping all the elements in the $o$ and $e$ arrays.
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n; cin >> n; int a = 0, b = 0; for (int i = 0; i < n; i++) { int x; cin >> x; if (x % 2 != i % 2) { if (i % 2 == 0) { a++; } else { b++; } } } if (a != b) { cout << -1 << endl; } else { cout << a << endl; } } int main() { int n; cin >> n; while (n--) { solve(); } }
1367
C
Social Distance
Polycarp and his friends want to visit a new restaurant. The restaurant has $n$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $1$ to $n$ in the order from left to right. The state of the restaurant is described by a string of length $n$ which contains characters "1" (the table is occupied) and "0" (the table is empty). Restaurant rules prohibit people to sit at a distance of $k$ or less from each other. That is, if a person sits at the table number $i$, then all tables with numbers from $i-k$ to $i+k$ (except for the $i$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $k$. For example, if $n=8$ and $k=2$, then: - strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant; - strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $k=2$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied. You are given a binary string $s$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $s$. Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied? For example, if $n=6$, $k=1$, $s=$ "100010", then the answer to the problem will be $1$, since only the table at position $3$ can be occupied such that the rules are still satisfied.
Let's split a given string into blocks of consecutive zeros. Then in each such block, you can independently put the maximum number of people who fit in it. But there are three cases to consider. If the current block is not the first and not the last, then there are ones at the border and this means that the first $k$ tables of the current block and the last $k$ are prohibited. Therefore, remove these zeroes from the string. If the current block is the first, then the one is at the end and you need to delete the last $k$ zeros. If the current block is the last, then in the beginning there is one and you need to delete the first $k$ zeros. Now all the tables in each block are free, then in each block we can put $\lfloor \frac{\text{number of zeros}}{k} \rfloor$. Sum these values over all blocks.
[ "constructive algorithms", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int test = 1; test <= t; test++) { int n, k; cin >> n >> k; string s; cin >> s; int res = 0; for (int i = 0; i < n;) { int j = i + 1; for (; j < n && s[j] != '1'; j++); int left = s[i] == '1' ? k : 0; int right = j < n && s[j] == '1' ? k : 0; int len = j - i; if (left == k) { len--; } len -= left + right; if (len > 0) { res += (len + k) / (k + 1); } i = j; } cout << res << endl; } return 0; }
1367
D
Task On The Board
Polycarp wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input. After that, he erased some letters from the string $s$, and he rewrote the remaining letters in \textbf{any} order. As a result, he got some new string $t$. You have to find it with some additional information. Suppose that the string $t$ has length $m$ and the characters are numbered from left to right from $1$ to $m$. You are given a sequence of $m$ integers: $b_1, b_2, \ldots, b_m$, where $b_i$ is the sum of the distances $|i-j|$ from the index $i$ to all such indices $j$ that $t_j > t_i$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $b_i$, Polycarp finds all such indices $j$ that the index $j$ contains a letter that is later in the alphabet than $t_i$ and sums all the values $|i-j|$. For example, if $t$ = "abzb", then: - since $t_1$='a', all other indices contain letters which are later in the alphabet, that is: $b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$; - since $t_2$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_2=|2-3|=1$; - since $t_3$='z', then there are no indexes $j$ such that $t_j>t_i$, thus $b_3=0$; - since $t_4$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_4=|4-3|=1$. Thus, if $t$ = "abzb", then $b=[6,1,0,1]$. Given the string $s$ and the array $b$, find any possible string $t$ for which the following two requirements are fulfilled simultaneously: - $t$ is obtained from $s$ by erasing some letters (possibly zero) and then writing the rest in \textbf{any} order; - the array, constructed from the string $t$ according to the rules above, equals to the array $b$ specified in the input data.
We will construct the string $t$, starting with the largest letters. Note that if $b_i = 0$, then the $i$-th letter of the string $t$ is maximal, so we know that the $i$-th letter affect all $b_j \ne 0$. While the string $t$ is not completely constructed, we will do the following: Find all $i$ such that $b_i = 0$ and the $i$-th character of string $t$ is not placed; Put on all these positions $i$ in the string $t$ the maximum letter not used in the string $t$ (there should be a sufficient number of letters in the string $s$); Subtract $|i - j|$ from all $b_j \ne 0$.
[ "constructive algorithms", "greedy", "implementation", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int q; cin >> q; forn(qq, q) { string s; cin >> s; int n; cin >> n; vector<int> b(n); forn(i, n) cin >> b[i]; vector<vector<int>> groups; while (true) { vector<int> pos; forn(i, n) if (b[i] == 0) pos.push_back(i); if (pos.empty()) break; groups.push_back(pos); forn(i, n) if (b[i] == 0) b[i] = INT_MAX; else for (int pp: pos) b[i] -= abs(i - pp); } map<char, int> cnts; forn(i, s.size()) cnts[s[i]]++; auto j = cnts.rbegin(); string t(n, '?'); for (auto g: groups) { while (j->second < g.size()) j++; for (int pp: g) t[pp] = j->first; j++; } cout << t << endl; } }
1367
E
Necklace Assembly
The store sells $n$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them. A necklace is a set of beads connected in a circle. For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): And the following necklaces cannot be assembled from beads sold in the store: \begin{center} {\small The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store.} \end{center} We call a necklace $k$-beautiful if, when it is turned clockwise by $k$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. As you can see, this necklace is, for example, $3$-beautiful, $6$-beautiful, $9$-beautiful, and so on, but it is not $1$-beautiful or $2$-beautiful.In particular, a necklace of length $1$ is $k$-beautiful for any integer $k$. A necklace that consists of beads of the same color is also beautiful for any $k$. You are given the integers $n$ and $k$, and also the string $s$ containing $n$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $k$-beautiful necklace you can assemble.
Let's iterate over the $m$ - length of the $k$-beautiful necklace. For each position $i$, make an edge to the position $p[i] = (i + k) \bmod m$, where $a \bmod b$ - is the remainder of dividing $a$ by $b$. What is a cyclic shift by $k$ in this construction? A bead located at position $i$ will go along the edge to position $p[i]$. Consider all the cycles of a graph constructed on $p$. You may notice that if only equal letters are found in each cycle, then with a cyclic shift by $k$ the graph and the string will remain unchanged. Thus, in order to check whether it is possible to make a $k$-beautiful necklace of length $m$, you need to make a graph $p$, find the cycles in it and check whether it is possible to distribute the letters from the string $s$ in cycles such that each cycle have equal letters. The last part of the solution can be done with simple greedy.
[ "brute force", "dfs and similar", "dp", "graphs", "greedy", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; while (test--) { int n, k; cin >> n >> k; string s; cin >> s; vector<int> cnt(26); for (char c : s) { cnt[c - 'a']++; } for (int len = n; len >= 1; len--) { vector<bool> used(len); vector<int> cycles; for (int i = 0; i < len; i++) { if (used[i]) { continue; } int j = (i + k) % len; used[i] = true; cycles.push_back(0); cycles.back()++; while (!used[j]) { cycles.back()++; used[j] = true; j = (j + k) % len; } } vector<int> cur_cnt(cnt); sort(cycles.begin(), cycles.end()); sort(cur_cnt.begin(), cur_cnt.end()); bool can_fill = true; while (!cycles.empty()) { if (cur_cnt.back() < cycles.back()) { can_fill = false; break; } else { cur_cnt.back() -= cycles.back(); cycles.pop_back(); sort(cur_cnt.begin(), cur_cnt.end()); } } if (can_fill) { cout << len << endl; break; } } } }
1367
F2
Flying Sort (Hard Version)
\textbf{This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem.} You are given an array $a$ of $n$ integers \textbf{(the given array can contain equal elements)}. You can perform the following operations on array elements: - choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the \textbf{begin} of the array; - choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the \textbf{end} of the array. For example, if $n = 5$, $a = [4, 7, 2, 2, 9]$, then the following sequence of operations can be performed: - after performing the operation of the first type to the second element, the array $a$ will become $[7, 4, 2, 2, 9]$; - after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 2, 9, 4]$. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the $a$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $a[1] \le a[2] \le \ldots \le a[n]$.
Let's replace each number $a_i$ with the number of unique numbers less than $a_i$. For example, the array $a=[3, 7, 1, 2, 1, 3]$ will be replaced by $[2, 3, 0, 1, 0, 2]$. Note that the values of the numbers themselves were not important to us, only the order between them was important. Let's sort such an array. Let's see what maximum length of the segment from the array $a$ is already sorted (it forms a subsequence). This segment can be left in place, and all other numbers can be moved either to the beginning or to the end. That is, the task came down to finding the maximum sorted subsequence in the array. This problem can be solved with the help of simple dynamic programming. Let $dp[i]$ -- be the maximum length of a subsequence ending in position $i$. To calculate it, we will find the closest past position, which also has the value $a[i]$ and the position with value $a[i]-1$ (lower numbers cannot be used, since $a[i]-1$ must stand between them). Any of these positions can be extended, so we take the maximum out of them and add 1. It is necessary to separately consider the first numbers in the subsequence and the last, since the first should include their suffix, and the last should have their prefix.
[ "binary search", "data structures", "dp", "greedy", "sortings", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n; cin >> n; vector<int> v(n); vector<pair<int, int>> a(n); for (int i = 0; i < n; i++) { cin >> v[i]; a[i] = {v[i], i}; } sort(a.begin(), a.end()); vector<int> p(n); int j = 0; unordered_multiset<int> next; for (int i = 0; i < n; i++) { if (i > 0 && a[i].first != a[i - 1].first) { j++; } p[a[i].second] = j; next.insert(j); } unordered_map<int, int> d; vector<int> dp1(n), dp2(n), dp3(n), cnt(n); for (int i = 0; i < n; i++) { if (next.count(p[i])) { next.erase(next.find(p[i])); } if (d.count(p[i] - 1)) { if (!d.count(p[i])) { dp2[i] = max(dp2[i], dp1[d[p[i] - 1]] + 1); if (!next.count(p[i] - 1)) { dp2[i] = max(dp2[i], dp2[d[p[i] - 1]] + 1); } } if (!next.count(p[i] - 1)) { dp3[i] = max(dp3[i], dp2[d[p[i] - 1]] + 1); } dp3[i] = max(dp3[i], dp1[d[p[i] - 1]] + 1); } if (d.count(p[i])) { dp3[i] = max(dp3[i], dp3[d[p[i]]] + 1); dp2[i] = max(dp2[i], dp2[d[p[i]]] + 1); dp1[i] = dp1[d[p[i]]] + 1; } else { dp1[i] = 1; } dp2[i] = max(dp2[i], dp1[i]); dp3[i] = max(dp3[i], dp2[i]); d[p[i]] = i; } cout << n - *max_element(dp3.begin(), dp3.end()) << "\n"; } int main() { int n; cin >> n; while (n--) { solve(); } }
1368
A
C+=
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a =$2$, b =$3$ changes the value of a to $5$ (the value of b does not change). In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b \textbf{strictly greater} than a given value $n$. What is the smallest number of operations he has to perform?
After any operation either $a$ or $b$ becomes $a + b$. Out of the two options, clearly it is better to increase the smaller number. For example, with numbers $2, 3$ we can either get a pair $2, 5$ or $3, 5$; to obtain larger numbers, the last pair is better in every way. With this we can just simulate the process and count the number of steps. The worst case is $a = b = 1$, $n = 10^9$, where each new addition produces the next element of the Fibonacci sequence. At this point we can just run the simulation and find out that $43$ steps are always enough. In general, Fibonacci sequence grows exponentially, thus $O(\log n)$ steps are needed. Find a closed formula for the answer. For simplicity assume $a \leq b$,
[ "brute force", "greedy", "implementation", "math" ]
800
null
1368
B
Codeforces Subsequences
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least $k$ subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string $s$ is a subset of ten characters of $s$ that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: {\textbf{codeforces}isawesome}, {\textbf{codeforce}si\textbf{s}awesome}, {\textbf{codeforce}sisawe\textbf{s}ome}, {\textbf{codeforc}esisaw\textbf{es}ome}. Help Karl find any shortest string that contains at least $k$ codeforces subsequences.
Suppose that instead of codeforces subsequences we're looking for, say, abcde subsequences. Then in an optimal string all a's appear at the front. Indeed, moving any other occurence of a to the front will leave all the other occurences intact, and can only possibly create new ones. For a similar reason, all b's should immediately follow, then go all c's, and so on. The only question is how many a's, b's, etc should we take. The answer is we should have quantities of each letter as close as possible to each other. Indeed, the number of subsequences is $n_a \times n_b \times \ldots \times n_e$, where $n_a, n_b, \ldots$ are the number of occurences of each letter. If, say, $n_a - n_b > 1$, then it is not hard to show that transforming an a to a b increases the product. Now the optimal distribution can be obtained simply by increasing $n_a, n_b, \ldots$ one by one in a loop. We should stop once the product is at least $k$. This approach will, however, not work quite as well if the subsequence has repeated letters. Still, it is natural to expect that the same pattern applies to optimal strings with codeforces subsequences: it has a lot of unique letters, and repeated letters are far apart. It was hardly necessary, but here's one way to prove that the pattern works (math and casework alert): Letters d, f, r, s should form consecutive blocks. If, say, two d's are separated by other letters, we can look which d is present in fewer number of subsequences, and more it next to the more popular one. The same argument works for all other letters. It doesn't make sense to put anything other than e's between d's and f's. Indeed, any other letter won't be present in any subsequences. Similarly, there can only be o's between f's and r's. Now we know the string looks like ???dddeeefffooorrr???sss. Finally, only c's and o's can precede d's, and it doesn't make sense to place o's before c's. Similarly, c's and e's in this order occupy the space between r's and s's. It follows that the same solution as above can be applied to solve this problem. As mentioned above, the problem is not that easy in general case when there are a lot of repeated letters. Still, is it possible to do? Any solution faster than brute-force would be interesting, or even some ideas or observations. I find it much harder to create a good easy problem than a good hard problem. This position in paricular gave me a lot of trouble, we had to scratch three or four other versions. Not to say the result is very inspiring, but the previous ones were even worse... What do you except to see in a good easy problem, say, up to Div1A? What are you favourite easy problems of this level? I would especially appreciate answers from high-rated coders.
[ "brute force", "constructive algorithms", "greedy", "math", "strings" ]
1,500
null
1368
C
Even Picture
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction. To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: - The picture is \textbf{connected}, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). - Each gray cell has an \textbf{even number of gray neighbours}. - There are \textbf{exactly $n$ gray cells with all gray neighbours}. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed). Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $n$. Help him, and provide any example of a beautiful picture. To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $(0, 0)$, axes $0x$ and $0y$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.
The sample picture was a red herring, it's hard to generalize to work for arbitrary $n$. After drawing for a while you may come up with something like this: or like this: or something even more complicated. Of course, having a simpler construction (like the first one) saves time on implementation compared to other ones. Don't settle for a solution if it feels too clunky, take a moment and see if you can make it simpler. How to minimize the total number of squares for a given $n$? The squares-on-a-diagonal construction in the first picture is pretty efficient, but e.g. for $n=4$ the picture in the sample has fewer squares. How does the minimum-square picture look in general?
[ "constructive algorithms" ]
1,500
null
1368
D
AND, OR and square sum
Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero). After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve?
Let's look at a single operation $x, y \to x~\mathsf{AND}~y, x~\mathsf{OR}~y$, let the last two be $z$ and $w$ respectively. We can notice that $x + y = z + w$. Indeed, looking at each bit separately we can see that the number of $1$'s in this bit is preserved. Clearly $z \leq w$, and suppose also that $x \leq y$. Since the sum is preserved, we must have $z = x - d$, $w = y + d$ for some non-negative $d$. But then the sum of squares of all numbers changes by $z^2 + w^2 - x^2 - y^2$. Substituting for $z$ and $w$ and simplifying, this is equal to $2d(d + y - x)$, which is positive when $d > 0$. Side note: an easier (?) way to spot the same thing is to remember that $f(x) = x^2$ is convex, thus moving two points on the parabola away from each other by the same amount increases the sum of values. It follows that any operation increases the square sum (as long as any numbers change), and we should keep doing operations while we can. When can we no longer make meaningful operations? At that point all numbers should be submasks of each other. The only way that could happen is when for any bit only several largest numbers have $1$ in that position. We also know that the number of $1$'s in each bit across all numbers is preserved. Thus, it's easy to recover the final configuration: for each bit count the number of $1$'s, and move all these $1$'s to the last (=greatest) numbers. For example, for the array $[1, 2, 3, 4, 5, 6, 7]$ there are four $1$'s in each of the smallest three bits, thus the final configuration is $[0, 0, 0, 7, 7, 7, 7]$. Finally, print the sum of squares of all these numbers. The total complexity is $O(n \log_2 A)$, where $A$ is the largest possible number (thus $\log_2 A$ is roughly the number of bits involved). How to find the smallest number of operations we need to make until there are no more we can make? Any solution polynomial in $n$ and $\log_2 \max A$ would be interesting.
[ "bitmasks", "greedy", "math" ]
1,700
null
1368
E
Ski Accidents
Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are \textbf{no directed cycles} formed by the tracks. There are \textbf{at most two tracks leaving each spot}, but many tracks may enter the same spot. A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks. Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. Formally, after closing some of the spots, \textbf{there should not be a path that consists of two or more tracks}. Arthur doesn't want to close too many spots. He will be happy to find any way to close \textbf{at most $\frac{4}{7}n$ spots} so that the remaining part is safe. Help him find any suitable way to do so.
Let's consider vertices from $1$ to $n$ (that is, in topological order). We divide them into three sets $V_0$, $V_1$, $V_2$: $V_0$ contains all vertices that only have incoming edges from $V_2$; $V_1$ contains all vertices that have an incoming edge from $V_0$, but not from $V_1$; $V_2$ contains all vertices that have an incoming edge from $V_1$. It is not hard to see that erasing all vertices in $V_2$ leaves no two-edge paths. The same solution can be simply rephrased as: go from left to right, and remove current vertex if it is at the end of a two-edge path. Why does this work? Every vertex of $V_2$ has to have at least one incoming edge from $V_1$. There are at most $2|V_1|$ such edges, thus $|V_2| \leq 2|V_1|$, and $|V_1| \geq |V_2| / 2$. Similarly, $|V_0| \geq |V_1| / 2 \geq |V_2| / 4$. But then $n = |V_0| + |V_1| + |V_2| \geq |V_2| (1 + 1/2 + 1/4) = 7|V_2|/4$, thus $|V_2| \leq 4n/7$. This is very easy to implement in $O(n)$ time. It's not hard to construct a test where $n/2$ spots have to be closed. However, I could not find a test where more that $n/2$ spots need to be closed, nor do I know of a solution that closes less than $4n/7$ spots in the worst case. In other words, if $\alpha$ is the optimal constant such that $\alpha n + o(n)$ spots need to be closed, we know that $1/2 \leq \alpha \leq 4/7$. Can I find better bounds for $\alpha$, or even find its precise value? Huge thanks to our tester kocko for pointing out many mistakes in an old version of this problem's statement, and even proposing a revision of a big part of the statement which we've adopted. Sadly, many other parts of the statement still were not very clear...
[ "constructive algorithms", "graphs", "greedy" ]
2,500
null
1368
F
Lamps on a Circle
This is an interactive problem. John and his imaginary friend play a game. There are $n$ lamps arranged in a circle. Lamps are numbered $1$ through $n$ in clockwise order, that is, lamps $i$ and $i + 1$ are adjacent for any $i = 1, \ldots, n - 1$, and also lamps $n$ and $1$ are adjacent. Initially all lamps are turned off. John and his friend take turns, with John moving first. On his turn John can choose to terminate the game, or to make a move. To make a move, John can choose any positive number $k$ and turn any $k$ lamps of his choosing on. In response to this move, John's friend will choose $k$ \textbf{consecutive} lamps and turn all of them off (the lamps in the range that were off before this move stay off). Note that the value of $k$ is the same as John's number on his last move. For example, if $n = 5$ and John have just turned three lamps on, John's friend may choose to turn off lamps $1, 2, 3$, or $2, 3, 4$, or $3, 4, 5$, or $4, 5, 1$, or $5, 1, 2$. After this, John may choose to terminate or move again, and so on. However, John can not make more than $10^4$ moves. John wants to maximize the number of lamps turned on at the end of the game, while his friend wants to minimize this number. Your task is to provide a strategy for John to achieve optimal result. Your program will play interactively for John against the jury's interactor program playing for John's friend. Suppose there are $n$ lamps in the game. Let $R(n)$ be the number of turned on lamps at the end of the game if both players act optimally. Your program has to terminate the game with at least $R(n)$ turned on lamps within $10^4$ moves. Refer to Interaction section below for interaction details. For technical reasons \textbf{hacks for this problem are disabled.}
Let try to come up with an upper bound on $R(n)$. Let $x$ be the number of currently turned on lamps. Consider our last move that resulted in increasing $x$ (after the response was made), and suppose it turned on $k$ lamps. If the opponent could then find a segment of $k$ consecutive lamps and turn them off, the move could be reverted. From this we can conclude that $x$ could not be too large. Indeed, after the move $x + k$ lamps should have been divided into segments of length at most $k - 1$ each (since the opponent couldn't turn $k$ lamps off), separated by turned off lamps. The number of segments should have been at least $\frac{x + k}{k - 1}$, and the same bound applies to the number of separating lamps. Thus we must have had $x + k + \frac{x + k}{k - 1} \leq n$. After some boring transformations we obtain $x \leq n - k - \frac{n}{k} + 1$. It follows that $x$ can not be increased past this threshold with turning on $k$ lamps. This implies that $x$ can not be increased past $\max_k \left(n - k - \frac{n}{k} + 1\right)$ with any move, thus $R(n) \leq \max_k \left(n - k - \left\lceil\frac{n}{k}\right\rceil + 1\right)$. On the other hand, let's take such a $k$ that maximizes $n - k - \left\lceil\frac{n}{k}\right\rceil + 1$, and adopt the following strategy: Pick $\left\lceil\frac{n}{k}\right\rceil$ lamps that divide the circle into segments of length $\leq k - 1$ each, and never turn these lamps on. We can choose these lamps greedily at distance $k$ from each other, until we go full circle (at that point the distance from the last to the first lamp may be less than $k$). On each move, turn on any $k$ lamps except for the forbidden ones. Since the turned on lamps never form a segment of length $k$, we will successfully increase $x$ with this move. We stop once there are less than $k$ non-forbidden lamps to turn on. At this point we will have $x \geq n - \left\lceil\frac{n}{k}\right\rceil - k + 1$, thus $R(n)$ can not be less than this value. We've determined that $R(n) = \max_k \left(n - k - \left\lceil\frac{n}{k}\right\rceil + 1\right)$, and provided a quite simple strategy to achieve this result. For large $n$, the maximum is attained at $k \approx \sqrt{n}$, thus $R(n) \approx n - 2\sqrt{n}$. If the first player wants to minimize the number of turns until $R(n)$ lamps are lit, and the second player wants to maximize it, what is the resulting number of turns $T(n)$ is going to be? Precise formula would be awesome, but asymptotics or interesting bounds for $T(n)$ would be interesting too.
[ "games", "implementation", "interactive", "math" ]
2,600
null
1368
G
Shifting Dominoes
Bill likes to play with dominoes. He took an $n \times m$ board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two dominoes cover the same cell twice). After that Bill decided to play with the covered board and share some photos of it on social media. First, he removes exactly one domino from the board, freeing two of the cells. Next, he moves dominoes around. A domino can only be moved \textbf{along the line parallel to its longer side}. A move in the chosen direction is possible if the next cell in this direction is currently free. Bill doesn't want to lose track of what the original tiling looks like, so he makes sure that at any point each domino \textbf{shares at least one cell with its original position}. After removing a domino and making several (possibly, zero) moves Bill takes a photo of the board and posts it. However, with the amount of filters Bill is using, domino borders are not visible, so \textbf{only the two free cells of the board} can be identified. When the photo is posted, Bill reverts the board to its original state and starts the process again. Bill wants to post as many photos as possible, but he will not post any photo twice. How many distinct photos can he take? Recall that photos are different if the pairs of free cells in the photos are different.
Let's think of how a certain cell can be freed up. One way is to just lift the domino covering it from the start. If we didn't do it, then we must move the domino covering the cell, and there is exactly one way of doing so. But at this point the cell we've moved to should have been free. We can follow this chain of events, and we must eventually arrive to a cell that was covered by the initially removed domino. This is more readily seen if we draw a graph with vertices being cells, and edges leading from the cell freed up by moving a domino to the cell becoming occupied by doing so. Note that some of the cells are impossible to free up with such a move. Let us study this graph a bit more. If we color the board like a chessboard, we can see that edges always connect cells of the same color, so the two subgraphs for white and black cells are independent. Further, since initially a white and a black cell are freed, the two free cells will always have different colors. In this graph each vertex (= cell) has out-degree at most $1$. In general directed graphs of this kind are called functional graphs, and look like a bunch of trees linked to directed cycles. However, it turns out that our graph can not have cycles! To prove this, let's look a how this cycle would look like: Centers of all the cells in a cycle form a lattice polygon. The area of such a polygon can be found with Pick's formula: $S = I + B / 2 - 1$, where $I$ and $B$ is the number of lattice points inside and on the boundary respectively. However, we can observe that: $B$ is the length of the boundary. The boundary can be broken into segments of length $2$. The length of upward and downward arrows is the same, therefore the length of vertical borders is divisible by $4$, same for horizontal arrows. Thus $B$ is divisible by $4$, and $B / 2$ must be even. Inside of the polygon can be broken down into $2 \times 2$ squares, therefore $S$ must be even. $I = S - B / 2 + 1$ should therefore be odd. However, the inside of the cycle is isolated from the outside, and therefore should be independently tilable with dominoes. But the number of cells (= vertices) inside the cycle is odd, therefore it's impossible. Since our directed graph has no cycles, it must be a directed forest, which makes it much easier to handle. Now consider a pair of cells $c_1, c_2$ of different colors, and look at the paths $P_1$ and $P_2$ starting at these cells. If these paths reach the boundary without visiting the same domino, then the pair $c_1, c_2$ is impossible to free up, since we would have to remove at least two dominoes. If the paths do visit at least one common domino, then we argue that the pair is possible to free up. Indeed, consider the first domino $D$ on $P_1$ that is also visited by $P_2$. If we remove $D$, then the parts of $P_1$ and $P_2$ until $D$ can not intersect, thus it is possible to move dominoes to free $c_1$ and $c_2$ without trying to move any domino twice. To figure out the answer, consider the two forests $F_1$ and $F_2$ built up by black and white cells of the board. If we label each cell of each forest with the index of the domino covering this cell, then the answer is equal to the number of pairs of cells $c_1 \in F_1$, $c_2 \in F_2$ such that the paths starting at $c_1$ and $c_2$ have common labels. To actually compute the answer we will instead count the cell pairs with label-disjoint paths. This is now a fairly standard data structure problem. Construct Euler tours in both $F_1$ and $F_2$. Then, the subtree of each vertex is a segment in the Euler tour. For a cell $c_1 \in F_1$ labeled with domino $D$, suitable cells in $F_2$ are the ones not in the subtree of a cell sharing the label with $c_1$ or with any parent of $c_1$. Perform a DFS of $F_1$, following edges in reverse. When we enter a cell labeled $D$, locate the cell with this label in $F_2$ and mark all vertices in its subtree. At this point, we should add the number of unmarked cells in $F_2$ to the answer. When we leave the cell, revert to the previous configuration before marking the subtree. Implementation-wise, this can be done with a segment tree that supports adding on a segment (= subtree in the Euler tour), and finding the number of zeros (= unmarked cells). Segment tree is the most demanding component of the solution, thus the complexity is $O(nm \log (nm))$. What are the minimum and maximum possible answers among all tilings of the board of given dimensions $n$ and $m$? The final version of this problem is due to 300iq who proposed an interesting modification to my initial idea.
[ "data structures", "geometry", "graphs", "trees" ]
3,200
null
1368
H2
Breadboard Capacity (hard version)
This is a harder version of the problem H with modification queries. Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer. The component is built on top of a breadboard — a grid-like base for a microchip. The breadboard has $n$ rows and $m$ columns, and each row-column intersection contains a node. Also, on each side of the breadboard there are ports that can be attached to adjacent nodes. Left and right side have $n$ ports each, and top and bottom side have $m$ ports each. Each of the ports is connected on the outside to one of the parts bridged by the breadboard, and is colored red or blue respectively. Ports can be connected by wires going inside the breadboard. However, there are a few rules to follow: - Each wire should connect a red port with a blue port, and each port should be connected to at most one wire. - Each part of the wire should be horizontal or vertical, and turns are only possible at one of the nodes. - To avoid interference, wires can not have common parts of non-zero length (but may have common nodes). Also, a wire can not cover the same segment of non-zero length twice. The capacity of the breadboard is the largest number of red-blue wire connections that can be made subject to the rules above. For example, the breadboard above has capacity $7$, and one way to make seven connections is pictured below. Up to this point statements of both versions are identical. Differences follow below. As is common, specifications of the project change a lot during development, so coloring of the ports is not yet fixed. There are $q$ modifications to process, each of them has the form of "colors of all ports in a contiguous range along one of the sides are switched (red become blue, and blue become red)". All modifications are persistent, that is, the previous modifications are not undone before the next one is made. To estimate how bad the changes are, Lester and Delbert need to find the breadboard capacity after each change. Help them do this efficiently.
We are basically asked to find the maximum flow value from red ports to blue ports in the grid network. All edges can be assumed to be bidirectional and have capacity $1$. By Ford-Fulkerson theorem, the maximum flow value is equal to the minimum cut capacity. In our context it is convenient to think about minimum cut as a way to paint nodes inside the grid red and blue so that the number of edges connecting differently colored nodes is smallest possible. For a given coloring, let us construct a cut in the dual graph by connecting the faces separated by multicolored edges. Note that the cut can be decomposed into cycles, paths connecting two points on the border, and single edge cuts adjacent to the ports. We may assume that different parts of the cut do not cross each other since we can just reassign parts at the crossing. The following actions modify the cut without increasing its capacity (the number of crossed edges): Interior of any cycle can be recolored, which makes the cycle disappear. If a path connects a pair of adjacent sides, we may get rid of the path and instead cut/uncut ports in the corner separated by the path. A path connecting opposite sides can be transformed into a straight segment, possibly with cutting/uncutting some ports. Applying these operations to any minimum cut, we can obtain a minimum cut that only consists of port cuts and straight segments parallel to one of the sides. Note that a port cut is essentially equivalent to recoloring of that port, with increase $1$ towards the cut capacity. Each straight segment contributes $n$ or $m$ to the capacity depending on the orientation. A minimum cut of the form above can be found with a simple linear dynamic programming. First, choose the direction of straight cuts (say, vertical). All ports along each vertical side should be recolored to the same color. Then, proceeding in the horizontal direction we may decide to recolor ports adjacent to horizontal sides, and/or to make a straight vertical cut. We need to make sure that each connected part between the cuts has uniform color. In addition to the horizontal position, the only extra parameter for this DP is the color immediately behind the current vertical line. This solves the easy version of the problem. To solve the hard version, we need to combine this DP with lazy propagation segment tree. We will store a separate segment tree for each direction of straight cuts. Say, for vertical cuts, a node $[L, R)$ should store costs to properly recolor and/or make straight cuts in the horizontal range $[L, R)$ so that the leftmost/rightmost nodes are red/blue (all four options). Make sure to take fixing vertical sides into account when calculating the answer. Merging the cost values from two halves of a node segment follows directly from the original DP recalculation. To be able to make range flips fast enough, we need to store four more values - the answers assuming that the opposite sides take opposite colors instead of the same colors. Now to flip a node in the segment tree simply exchange the correct values with the opposite ones. Implementation details are left for the reader to work out. =) With this approach we are able to process each modification query in $O(\log n + \log m)$ time, although the constant factor is fairly large because of complicated merging process. Can you solve the same problem in 3D? The breadboard is now an $n \times m \times k$ parallelepiped, and there are $2(nm + nk + mk)$ adjacent ports.
[]
3,500
null
1369
A
FashionabLee
Lee is going to fashionably decorate his house for a party, using some regular convex polygons... Lee thinks a regular $n$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $OX$-axis and at least one of its edges is parallel to the $OY$-axis at the same time. Recall that a regular $n$-sided polygon is a convex polygon with $n$ vertices such that all the edges and angles are equal. Now he is shopping: the market has $t$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.
$\mathcal Complete\;\mathcal Proof :$ Proof by contradiction : One can prove that if two edges in a regular polygon make a $x < 180$ degrees angle, then for each edge $a$ there exist two another edges $b$ and $c$ such that $a$ and $b$ make a $x$ degrees angle as well as $a$ and $c$. (proof is left as an exercise for the reader) Consider a rotation such that an edge $a$ is parallel to $OX$-axis and an edge $b$ is parallel to $OY$-axis, then $a \perp b$ ($a$ and $b$ are perpendicular, i. e. the angle between them is $90$ degrees), we can see that there exist a third edge $c$ such that it's also parallel to $OX$-axis and a forth edge $d$ such that it's also parallel to $OY$-axis, so $a \perp d$ and $b \perp c$ and $c \perp d$. Our polygon is regular so all the angles are equal, so that the number of angles between $a$ and $b$ is equal to the number of angles between $b$ and $c$ and so on, also we know that a regular $n$-sided convex polygon has $n$ angles, so $n$ is divisible by $4$, contradiction!
[ "geometry", "math" ]
800
#include <iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; if(n % 4 == 0){ cout << "YES\n"; } else cout << "NO\n"; } }
1369
B
AccurateLee
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase \textbf{exactly one of them} (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing. Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the \textbf{shorter} string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner. Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves. Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$.
$\mathcal Complete\; \mathcal Proof$ : Realize that the answer is always non-descending, and we can't perform any operations on non-descending strings. First we know that we can't perform any operations on non-descending strings, so the answer to a non-descending string is itself. From now we consider our string $s$ to not to be non-descending. (i.e. there exist index $i$ such that $1 \le i \le n-1$ and $s_i > s_{i+1}$) Also realize that the remaining string wont be empty, so "0" is the cleanest possible answer, but we can't reach it probable. Now realize that leading zeroes and trailing ones can't be present in any operation. So they have to be in the answer, erase them from $s$, and add them to the answer for the modified $s$. From now we know that the string $s$ has no leading zeroes and/or trailing ones, and is not non-descending, so it starts with $1$ and ends with $0$. (why?) With some small paperwork, we will realize that the answer to a string that starts with $1$ and ends with $0$ is a single $0$(proof is bellow). So if the string $s$ is non-descending and it has $x$ leading zeroes and $y$ trailing ones($x$ and $y$ can be equal to zero), then the answer is $\underbrace{0\,0\dots0}_{x}\,0\,\underbrace{1\,1\dots1}_{y}$ (its $x+1$ zeroes and $y$ ones in order) $\mathcal The\;\mathcal Small\;\mathcal Paperwork:$ We will randomly perform operations until we can't do any more or the string's length is equal to $2$, but we wont erase the first $1$ and the last $0$, we want to prove that the remaining string's length is exactly $2$ after the process ends, proof by contradiction : So it's length is at least $3$, so we have at least two $1$ or at least two $0$. If we had two or more $0$ then the string $[s_1\,s_2\dots s_{n-1}]$ will not be non-descending(so we can perform more operations as we proved in STAR, but the process have ended, contradiction!) and if we had two or more $1$ then the string $[s_2\,s_3\dots s_n]$ will not be non-descending. So the length of the remaining string is exactly $2$, and we haven't erased first '1' and last '0', so the string is equal to "10", now erase '1' to get the cleanest string. Sorry if the proof seems too long and hard, i wanted to explain it accurately. ^-^
[ "greedy", "implementation", "strings" ]
1,200
#include <iostream> #include <string> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; string s; cin >> s; int sw = 1; for(int i = 1; i < s.size(); i++){ if(s[i] < s[i-1])sw = 0; } if(sw){ cout << s << '\n'; continue; } string ans; for(int i = 0; i < s.size(); i++){ if(s[i] == '1')break; ans.push_back('0'); } ans.push_back('0'); for(int i = s.size()-1; i >= 0; i--){ if(s[i] == '0')break; ans.push_back('1'); } cout << ans << '\n'; } }
1369
C
RationalLee
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $n$ integers, now it's time to distribute them between his friends rationally... Lee has $n$ integers $a_1, a_2, \ldots, a_n$ in his backpack and he has $k$ friends. Lee would like to distribute \textbf{all} integers in his backpack between his friends, such that the $i$-th friend will get exactly $w_i$ integers and each integer will be handed over to exactly one friend. Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get. Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.
$\mathcal Complete\; \mathcal Proof$ : First if $w_i = 1$ for some $i$, then assign the greatest element to $i$-th friends, it's always better obviously. Sort the elements in non-descending order and sort the friends in non-ascending order of $w_i$. Define $v_i$ the set of indices of elements to give to $i$-th friend. Also define $l_i$ the minimum element to give to $i$-th friend and $r_i$ the maximum element to give to $i$-th friend, and define $m = \max\limits_{1\,\le\,i\,\le\,k} w_i$. Now it's easy to see that the first element of $a$(the smallest element) is always equal to $l_i$ for some $i$, Indeed it's better to have the rest of $v_i$ equal to a small number except one of them, which should be equal to a very large number. So we can greedily assign $a_1$, $a_2$ ... $a_{{w_i}-1}$ to $v_i$, and then assign $a_n$ to it, also it's better to have $w_i = m$. One can prove that there exist an optimal distributing such that the set($\{a_1, a_2 \ldots a_{m-1}, a_n\}$) is equal to one of $v_i$-s(proof is blow). So add $a_1 + a_n$ to the answer for remaining elements of $a$(excluding the set) and remaining friends(excluding one of the friends with maximum $w_i$) and so, it will be optimal. Look at an optimal distributing (which maximizes sum of happiness), first element of $a$ is in $v_i$ for example, we want to prove that in at least one of the optimal distributings $w_i-1$ smallest elements of $a$ are in $v_i$ (including the first element), proof by contradiction: If at least one of the smallest $w_i-1$ elements is not in $v_i$, then call the smallest of them $x$, lets say it's in $v_j$, now add $x$ to $v_i$(and erase it from $v_j$), instead add a greater number than $x$ in $v_i$ to $v_j$ (it's at least two of them, and one of them is $r_i$, so there exist another one, erase it from $v_i$ and add it to $v_j$), it's easy to see that sum of happiness won't decrease that way, continue the process until all $w_i-1$ smallest elements are in $v_i$, so we have an optimal answer which has all $w_i-1$ smallest elements in $v_i$, contradiction! As we proved above, we have an optimal distributing such that all $w_i-1$ smallest elements are in $v_i$(for some $i$), now we want to prove that the greatest element is in $v_i$ in at least one of the optimal distributings, again proof by contradiction. Lets say it's not that way, so look at an optimal distributing such that first $w_i-1$ elements are in $v_i$ and $r_i$ is not equal to the greatest element(for some $i$), if there exist such $j$ that $r_i < l_j$, then swap $r_i$ and $l_j$, the resulting distributing has the same happiness, continue it until no such $j$ exist, now lets say the greatest element of $a$ is in $v_j$ for some $j$, also we know that $r_j$ is equal to the greatest element of $a$ and $l_j \le r_i$(if $r_i < l_j$ then the process of swapping is not finished, which is contradiction). So now we can swap $r_i$ and $r_j$, again the resulting distributing has happiness greater than or equal to the happiness of the optimal distributing(the one we chose in the beginning), and so, its also an optimal distributing, and $r_i$ is equal to the greatest element, we have found an optimal distributing such that first $w_i-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$), contradiction! Now we have proved that there exist an optimal distributing such that first $w_i-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$), call such optimal distributing STAR, and now the only remaining part is to prove that there exist an optimal distributing such that first $m-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$). See the whole algorithm, its like "we choose a permutation of friends then we do that greedy assignment to them one by one from left to right", now we want to prove that there exist an optimal distributing such that it's STAR and it's permutation is sorted in non-descending order of $w$, call them GOOD distributings. Again, proof by contradiction : Choose a distributing such that it's a STAR, it's permutation(called $p$) is not sorted in non-descending order of $w$(otherwise it's a GOOD distributing, contradiction!), so there exist an $i$ such that $w_{p_i} > w_{p_{i+1}}$, now swap them(i. e. swap $p_i$ and $p_{i+1}$ and then do the same greedy assignment using the modified permutation of friends), it's easy to see that happiness of friends after $i+1$ in permutation $p$ wont change, also happiness of friends before $i$ in the permutation wont change as well. Now look at the happiness of $p_i$ and $p_{i+1}$, you can realize that sum of happiness will increase. You really don't need to prove it like that, it's not time friendly at all. ^-^
[ "greedy", "math", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> #define ll long long #define fr first #define sc second #define int ll using namespace std; const int MN = 2e5+7; vector<int> v[MN]; signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, k; cin >> n >> k; for(int i = 0; i <= n; i++)v[i].clear(); ll a[n], w[k]; for(int i = 0; i < n; i++){ cin >> a[i]; } for(int i = 0; i < k; i++){ cin >> w[i]; } sort(w, w+k); sort(a, a+n); for(int i = 0; i < k/2; i++)swap(w[i], w[k-i-1]); int po = 0; for(int i = 0; i < n-k; i++){ while(w[po] == v[po].size()+1)po++; v[po].push_back(a[i]); } ll ans = 0; int qf = 1; for(int i = 0; i < k; i++){ ans += a[n-i-1]; if(v[i].size())ans += v[i][0]; else ans += a[n-qf], qf++; } cout << ans << '\n'; } }
1369
D
TediousLee
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes... Let's define a Rooted Dead Bush (RDB) of level $n$ as a rooted tree constructed as described below. A rooted dead bush of level $1$ is a single vertex. To construct an RDB of level $i$ we, at first, construct an RDB of level $i-1$, then for each vertex $u$: - if $u$ has no children then we will add a single child to it; - if $u$ has one child then we will add two children to it; - if $u$ has more than one child, then we will skip it. \begin{center} {\small Rooted Dead Bushes of level $1$, $2$ and $3$.} \end{center} Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw: \begin{center} {\small The center of the claw is the vertex with label $1$.} \end{center} Lee has a Rooted Dead Bush of level $n$. Initially, all vertices of his RDB are green. In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow. He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $10^9+7$.
$\mathcal Complete \mathcal Proof$ : First realize that a RDB of level $i$ is consisted of a vertex (the root of the RDB of level $i$) connected to the roots of two RDBs of level $i-2$ and a RDB of level $i-1$. Now define $dp_i$ equal to the answer for a RDB of level $i$. Also define $r_i$ equal to $1$ if Lee can achieve $dp_i$ yellow vertices in a RDB of level $i$ such that the root is green, and $0$ otherwise. It's easy to see that $dp_i$ is equal to either $2 \cdot dp_{i-2} + dp_{i-1}$ or $2 \cdot dp_{i-2} + dp_{i-1} + 4$. If both $r_{i-1}$ and $r_{i-2}$ are equal to $1$, then we can color the claw rooted at the root of the RDB, then $r_i = 0$ and $dp_i = 2 \cdot dp_{i-2} + dp_{i-1} + 4$. Also if either $r_{i-2}$ or $r_{i-1}$ is equal to $0$ then $r_i = 1$ and $dp_i = 2 \cdot dp_{i-2} + dp_{i-1}$. Challenge : Try solving problem D for $n \le 10^{18}$. (no matrix-multiplication)
[ "dp", "graphs", "greedy", "math", "trees" ]
1,900
#include <bits/stdc++.h> #define ll long long using namespace std; const int mod = int(1e9+7); const int MN = int(2e6+7); int dp[MN]; signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); dp[0] = dp[1] = 0; dp[2] = 4; for(int i = 3; i < MN; i++){ long long w = dp[i-1]; w += 2*dp[i-2] + (i % 3 == 2)*4; w %= mod; dp[i] = w; } int t; cin >> t; while(t--){ int n; cin >> n; n--; cout << dp[n]%mod << '\n'; } }
1369
E
DeadLee
Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020... There are $n$ different types of food and $m$ Lee's best friends. Lee has $w_i$ plates of the $i$-th type of food and each friend has two different favorite types of food: the $i$-th friend's favorite types of food are $x_i$ and $y_i$ ($x_i \ne y_i$). Lee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat \textbf{one plate of each of his favorite food types}. Each of the friends will go to the kitchen exactly once. The only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither $x_i$ nor $y_i$), he will eat Lee instead $\times\_\times$. Lee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself.
$\mathcal Complete\;\mathcal Solution$ : Define $s_i$ equal to the number of friends who likes food $i$. We want to proof that if $\forall 1 \le i \le m \Rightarrow s_i > w_i\, \text{or} \, s_i = 0$ then no answer exist, it can be proved easily by contradiction, just look at the last friend in any suitable permutation, he will eat Lee as there is no food for him. So if it was the case, then print Dead and terminate, otherwise place all the guys who likes food $i$ in the end of the permutation, they wont eat Lee as they can always eat food $i$, also it's always better to place them in the end, as if we place them in the end, then they wont eat two plates. Continue the process until no friends exist or no $i$ exist such that $w_i \ge s_i > 0$. Note that when we erase the friends, we have to update $s_i$, also if $s_i = 0$ we should erase food $i$ from the set of foods. $\mathcal Implementation\;\mathcal Details$ : Instead of erasing friends/foods, just remember if a friend/food is erased or not using another array. Also updating $s$ should not be that much hard(when marking $i$-th friend, decrease $s_{x_i}$ and $s_{y_i}$ by one, if there exist any), also you can have the food $i$ with maximum $w_i-s_i$ with a priority queue, or any other data structure in $O(\log_2{n})$. The whole solution will work in $O((n+m)\cdot \log_2{(n+m)}$ time, you can also try achieving $O(n+m)$ and then show-off it in the comment section ^_^.
[ "data structures", "dfs and similar", "greedy", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> #define ll long long #define fr first #define sc second #define pii pair<int, int> #define all(v) v.begin(), v.end() using namespace std; const int MN = 2e5+7; int x[MN], y[MN], s[MN], w[MN], mark[MN], colmark[MN]; vector<int> v[MN], a; vector<pii> f; priority_queue<pii, vector<pii>, greater<pii>> pq; signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); int n, m; cin >> n >> m; for(int i = 1; i <= n; i++)cin >> w[i]; for(int i = 0; i < m; i++){ cin >> x[i] >> y[i]; s[x[i]]++; s[y[i]]++; v[x[i]].push_back(i); v[y[i]].push_back(i); } for(int i = 1; i <= n; i++){ if(s[i])pq.push({max(0, s[i]-w[i]), i}); else colmark[i] = 1; } while(pq.size()){ auto q = pq.top(); pq.pop(); if(q.fr != max(0, s[q.sc]-w[q.sc]))continue; if(q.fr > 0){ cout << "DEAD\n"; exit(0); } int id = q.sc; vector<int> wt; for(auto u : v[id]){ if(mark[u])continue; a.push_back(u); if(x[u] == id) swap(x[u], y[u]); if(!colmark[x[u]])wt.push_back(x[u]); mark[u] = 1; } sort(all(wt)); for(int i = 0; i < wt.size(); i++){ s[wt[i]]--; if(i == wt.size()-1 || wt[i+1] != wt[i]){ if(s[wt[i]]){ if(max(0, s[wt[i]]-w[wt[i]]) == 0)colmark[wt[i]] = 1; pq.push({max(0, s[wt[i]]-w[wt[i]]), wt[i]}); } } } } cout << "ALIVE\n"; for(int i = 0; i < a.size()/2; i++)swap(a[i], a[a.size()-i-1]); for(auto u : a){ cout << u+1 << ' '; } cout << '\n'; }
1369
F
BareLee
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_i$ (which are determined and are known before the game begins, $s_i$ and $e_i$ may differ from round to round). The integer $s_i$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $a$) and will choose to write either $2 \cdot a$ or $a + 1$ instead. Whoever writes a number strictly greater than $e_i$ loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $s_i$ and $e_i$ in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
$\mathcal Complete \mathcal Proof$ : Define $w_{s,\,e}$ ($s \le e$) equal to $1$ if Lee can win the game when $s$ is written on the board, and equal to $0$ otherwise, also define $l_{s,\,e}$ the same way. This leads to a simple dp. Forget $l$ for now. Recall that a state ${i,\,j}$ of our dp is a losing state if $w_{i,\,j} = 0$, and is a winning state otherwise. You can guess $w_{s,\,e}$ for all $s$ in range $\frac e 4 < s \le e$ in $O(1)$, you don't have to store them : If $e$ is odd then it will be $w_{1,\,e} = 1, w{2,\,e} = 0, w{3,\,e} = 1 \dots w{e,\,e} = 0$, in other words if $e$ is odd, then if $s$ is odd too $w{s,\,e} = 0$, otherwise $w{s,\,e} = 1$. Prove it by induction, for $s = e$ it's correct, assume that for an integer $i$ ($1 \le i < e$) we have proved that the statement is correct for all $j$ where $i < j \le e$, now we want to prove the statement for $i$ : If $i$ is odd then both $i + 1$ and $2 \cdot i$ are winning states (as they are even), also if $i$ is even then $i + 1$ is odd, $i+1$ is smaller than $e$ so it's a losing state(induction assumption). From now we consider $e$ to be even. Also $\times 2$ operation is replacing $a$, the number on the board, with $2 \cdot a$, and $+ 1$ operation is the other move. For $\frac e 2 < s \le e$ whoever uses $\times 2$ operation will lose. So they all have to use $+ 1$ operation, so for ${e \over 2} < s \le e$ if $w$ is odd, then $w_{s,\,e} = 1$, otherwise $w_{s,\,e} = 0$. (it's obvious, it can be proved with a simple induction like the one in previous part) For ${e \over 4} < s \le {e \over 2}$, Lee can do a $\times 2$ operation in the first turn and he will win because his opponent is starting a losing state. For $s \le {e \over 4}$, $w_{s,\,e}$ is equal to $\displaystyle w_{s,\,\lfloor {e \over 4} \rfloor}$. (why?) Now it's time to calculate $l_{s,\,e}$. Remember, whoever writes an integer greater than $e$ will lose, so if $e < 2 \cdot s$ then the first guy can immediately lose. So $l_{s,\,e}$ for ${e \over 2} < s \le e$ is equal to $1$. And $l_{s,\,e}$ for $s \le {e \over 2}$ is equal to $\displaystyle w_{s,\,{\lfloor {e \over 2} \rfloor}}$. (why?)
[ "dfs and similar", "dp", "games" ]
2,700
#include <iostream> #include <vector> #include <string> #define fr first #define sc second #define ll long long #define int ll using namespace std; const int MN = 1e5+7; pair<int, int> c[MN]; int chk(ll s, ll e){ if(e == s)return 0; if(e == s+1)return 1; if(e & 1){ if(s & 1)return 0; return 1; } if(s <= e/4) return chk(s, e/4); if(s > (e/4)*2)return ((e-s)&1); else return 1; } int lck(ll s, ll e){ if(s*2 > e)return 1; int w = e/2 + 3; while(w*2 > e)w--; return chk(s, w); } signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); int n; cin >> n; for(int i = 0; i < n; i++){ ll x, y; cin >> x >> y; c[i] = {chk(x, y), lck(x, y)}; } int f = 1; int s = 0; for(int i = 0; i < n; i++){ if(f == 1 && s == 1)break; if(f == 0 && s == 0)break; if(s == 1) c[i].fr^=1, c[i].sc^=1; f = c[i].sc; s = c[i].fr; } cout << s << ' ' << f << '\n'; }
1370
A
Maximum GCD
Let's consider all integers in the range from $1$ to $n$ (inclusive). Among all pairs of \textbf{distinct} integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $\mathrm{gcd}(a, b)$, where $1 \leq a < b \leq n$. The greatest common divisor, $\mathrm{gcd}(a, b)$, of two positive integers $a$ and $b$ is the biggest integer that is a divisor of both $a$ and $b$.
Key Idea: Answer for any $n \ge 2$ is equal to $\lfloor{\frac{n}{2}}\rfloor$ . Solution: Let the maximum gcd be equal to $g$. Since the two numbers in a pair are distinct, one of them must be $\gt g$ and both of them must be divisible by $g$. The smallest multiple of $g$, greater than $g$, is $2 \cdot g$. Since each number in the pair must be $\le n$, we must have $2 \cdot g \le n$, or $g \le \lfloor{\frac{n}{2}}\rfloor$. We can achieve $g = \lfloor{\frac{n}{2}}\rfloor$, by choosing $\lfloor{\frac{n}{2}}\rfloor$ and $2 \cdot \lfloor{\frac{n}{2}}\rfloor$. Time Complexity: $O(1)$
[ "greedy", "implementation", "math", "number theory" ]
800
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int32_t main() { IOS; int t; cin >> t; while(t--) { int n; cin >> n; cout << n / 2 << endl; } return 0; }
1370
B
GCD Compression
Ashish has an array $a$ of consisting of $2n$ positive integers. He wants to compress $a$ into an array $b$ of size $n-1$. To do this, he first discards exactly $2$ (any two) elements from $a$. He then performs the following operation until there are no elements left in $a$: - Remove any two elements from $a$ and append their sum to $b$. The compressed array $b$ has to have a special property. The greatest common divisor ($\mathrm{gcd}$) of all its elements should be greater than $1$. Recall that the $\mathrm{gcd}$ of an array of positive integers is the biggest integer that is a divisor of all integers in the array. It can be proven that it is always possible to compress array $a$ into an array $b$ of size $n-1$ such that $gcd(b_1, b_2..., b_{n-1}) > 1$. Help Ashish find a way to do so.
Key Idea: It is always possible to form $n-1$ pairs of elements such that their gcd is divisible by $2$. Solution: We can pair up the odd numbers and even numbers separately so that the sum of numbers in each pair is divisible by $2$. Note that we can always form $n - 1$ pairs in the above manner because in the worst case, we would discard one odd number and one even number from $a$. If we discarded more than one even or odd numbers, we could instead form another pair with even sum. Time Complexity: $O(n)$
[ "constructive algorithms", "math", "number theory" ]
1,100
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n; int a[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; vector< int > even, odd; for(int i = 1; i <= 2 * n; i++) { cin >> a[i]; if(a[i] % 2) odd.push_back(i); else even.push_back(i); } vector< pair< int, int > > ans; for(int i = 0; i + 1 < odd.size(); i += 2) ans.push_back({odd[i], odd[i + 1]}); for(int i = 0; i + 1 < even.size(); i += 2) ans.push_back({even[i], even[i + 1]}); for(int i = 0; i < n - 1; i++) cout << ans[i].first << " " << ans[i].second << endl; } return 0; }
1370
C
Number Game
Ashishgup and FastestFinger play a game. They start with a number $n$ and play in turns. In each turn, a player can make \textbf{any one} of the following moves: - Divide $n$ by any of its odd divisors greater than $1$. - Subtract $1$ from $n$ if $n$ is greater than $1$. Divisors of a number include the number itself. The player who is \textbf{unable to make a move} loses the game. Ashishgup moves first. Determine the winner of the game if both of them play optimally.
Key Idea: FastestFinger wins for $n=1$ , $n=2^x$ where ($x>1$) and $n= 2 \cdot p$ where $p$ is a prime $\ge 3$ else Ashishgup wins. Solution: Let's analyse the problem for the following $3$ cases: Case $1$: n is oddHere Ashishgup can divide $n$ by itself, since it is odd and hence $\frac{n}{n} = 1$, and FastestFinger loses. Here $n = 1$ is an exception. Here Ashishgup can divide $n$ by itself, since it is odd and hence $\frac{n}{n} = 1$, and FastestFinger loses. Here $n = 1$ is an exception. Case $2$: $n$ is even and has no odd divisors greater than $1$Here $n$ is of the form $2^x$. As $n$ has no odd divisors greater than $1$, Ashishgup is forced to subtract it by $1$ making $n$ odd. So if $x > 1$, FastestFinger wins. For $x = 1$, $n - 1$ is equal to $1$, so Ashishgup wins. Here $n$ is of the form $2^x$. As $n$ has no odd divisors greater than $1$, Ashishgup is forced to subtract it by $1$ making $n$ odd. So if $x > 1$, FastestFinger wins. For $x = 1$, $n - 1$ is equal to $1$, so Ashishgup wins. Case $3$: $n$ is even and has odd divisorsIf $n$ is divisible by $4$ then Ashishgup can divide $n$ by its largest odd factor after which $n$ becomes of the form $2^x$ where $x \gt 1$, so Ashishgup wins. Otherwise $n$ must be of the form $2 \cdot p$, where $p$ is odd. If $p$ is prime, Ashishgup loses since he can either reduce $n$ by $1$ or divide it by $p$ both of which would be losing for him. If $p$ is not prime then $p$ must be of the form $p_1 \cdot p_2$ where $p_1$ is prime and $p_2$ is any odd number $\gt 1$. Ashishgup can win by dividing $n$ by $p_2$. If $n$ is divisible by $4$ then Ashishgup can divide $n$ by its largest odd factor after which $n$ becomes of the form $2^x$ where $x \gt 1$, so Ashishgup wins. Otherwise $n$ must be of the form $2 \cdot p$, where $p$ is odd. If $p$ is prime, Ashishgup loses since he can either reduce $n$ by $1$ or divide it by $p$ both of which would be losing for him. If $p$ is not prime then $p$ must be of the form $p_1 \cdot p_2$ where $p_1$ is prime and $p_2$ is any odd number $\gt 1$. Ashishgup can win by dividing $n$ by $p_2$.
[ "games", "math", "number theory" ]
1,400
#include< bits/stdc++.h > using namespace std; const int N = 50000; void player_1(){ cout << "Ashishgup" << endl; } void player_2(){ cout << "FastestFinger" << endl; } bool check_prime(int n){ for(int i = 2; i < min(N, n); i++) if(n % i == 0) return 0; return 1; } int main(){ int tc; cin >> tc; while(tc--){ int n; cin >> n; bool lose = (n == 1); if(n > 2 && n % 2 == 0){ if((n & (n — 1)) == 0) lose = 1; else if(n % 4 != 0 && check_prime(n / 2)) lose = 1; } if(lose) player_2(); else player_1(); } }
1370
D
Odd-Even Subsequence
Ashish has an array $a$ of size $n$. A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements. Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between: - The maximum among all elements at odd indices of $s$. - The maximum among all elements at even indices of $s$. Note that the index of an element is its index in $s$, rather than its index in $a$. The positions are numbered from $1$. So, the cost of $s$ is equal to $min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$. For example, the cost of $\{7, 5, 6\}$ is $min( max(7, 6), max(5) ) = min(7, 5) = 5$. Help him find the minimum cost of a subsequence of size $k$.
Key Idea: Binary search over the answer and check if given $x$, it is possible to form a subsequence of length at least $k$ such that either all elements at odd indices or even indices are $\le x$. Solution: Let us binary search over the answer and fix if the answer comes from elements at odd or even indices in the subsequence. Suppose we want to find if there exists a subsequence of length at least $k$ such that the elements at odd indices are $\le x$. We will construct the subsequence greedily. Let's iterate on the array from left to right. Suppose we are at index $i$ in the array and the current length of the subsequence formed is $l$. If $l$ is odd, the next added element would be at an even index. In this case, we do not care about what this element is as we only want elements at odd indices to be $\le x$. So, in this case, we add $a_i$ to the subsequence. If $l$ is even, then the next added element would be at an odd index, so, it must be $\le x$. If $a_i \le x$, we can add $a_i$ to the subsequence, otherwise we do not add $a_i$ to the subsequence and continue to the next element in $a$. Note that we can do a similar greedy construction for elements at even indices. If the length of the subsequence formed is $\ge k$ (either by construction from odd indices or even indices), then the answer can be equal to $x$ and we can reduce the upper bound of the binary search otherwise we increase the lower bound. Time Complexity - $O(n \cdot log_2 (A_i))$ or $O(n \cdot log_2 (n))$
[ "binary search", "dp", "dsu", "greedy", "implementation" ]
2,000
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, k; int a[N]; bool check(int x, int cur) { int ans = 0; for(int i = 1; i <= n; i++) { if(!cur) { ans++; cur ^= 1; } else { if(a[i] <= x) { ans++; cur ^= 1; } } } return ans >= k; } int binsearch(int lo, int hi) { while(lo < hi) { int mid = (lo + hi) / 2; if(check(mid, 0) || check(mid, 1)) hi = mid; else lo = mid + 1; } return lo; } int32_t main() { IOS; cin >> n >> k; for(int i = 1; i <= n; i++) cin >> a[i]; int ans = binsearch(1, 1e9); cout << ans; return 0; }
1370
E
Binary Subsequence Rotation
Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $s$ into $t$ using the following operation as few times as possible. In one operation, he can choose any subsequence of $s$ and rotate it clockwise once. For example, if $s = 1\textbf{1}101\textbf{00}$, he can choose a subsequence corresponding to indices ($1$-based) $\{2, 6, 7 \}$ and rotate them clockwise. The resulting string would then be $s = 1\textbf{0}101\textbf{10}$. A string $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the ordering of the remaining characters. To perform a clockwise rotation on a sequence $c$ of size $k$ is to perform an operation which sets $c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$ simultaneously. Determine the minimum number of operations Naman has to perform to convert $s$ into $t$ or say that it is impossible.
Key Idea: Firstly, if $s$ is not an anagram of $t$, it is impossible to convert $s$ to $t$ - since total number of $0$s and $1$s are conserved. However, if they are anagrams, we can always convert $s$ to $t$. We can ignore all the indices where $s_i = t_i$ as it is never optimal to include those indices in a rotation. The remaining indices must be satisfy $s_i = 0, t_i = 1$ or $s_i = 1, t_i = 0$. In the optimal answer, the chosen subsequences should be of the form 01010101... or 10101010... Solution: There are many approaches to solving the problem, all revolving around the key idea. We can greedily find the minimum number of chains of alternating 0 and 1 that the string can be broken down into - using faster ways of simulation, such as a counter-based for loop or using sets and deleting successive indices, etc. However, we will discuss an elegant approach which allows us to solve the problem and also prove its optimality. Moreover, it allows us to solve the problem for queries of the form $(l, r)$ - which denotes the answer for the strings $s[l,r]$ and $t[l,r]$ respectively. Logic: Let's create an array $a$ with values from $(-1, 0, 1)$ as follows: If $s_i = t_i$, $a_i = 0$ Else if $s_i = 1$, $a_i = 1$ Else $a_i = -1$ Proof: The chosen subsequences must be of the form 01010101 or 10101010 (alternating 0s and 1s). If there are two consecutive $0$s or $1$s we can remove any one of them as applying the rotation operation could only affect one of them. The maximum absolute value of subarray sum in $a$ is a lower bound on the answer. Let the sum of any subarray in $a$ be $c$. We can assume that $c \ge 0$ (otherwise we can interchange $1$ and $-1$). In any move, $c$ cannot be reduced by more than $1$, since we must choose subsequences of the form 010101 or 101010. We can achieve the above lower bound, and hence it is the answer. To prove the claim, we just need to show that in every operation, we can reduce the value of maximum absolute subarray sum by $1$ (if there are multiple such subarrays, then we must reduce all of them by $1$). For the above, a key realization is: suppose the maximum comes from a subarray $(l, r)$ with a positive sum. Then it is necessary that on both sides of its endpoints if there is an element, it must be $-1$ (we can ignore the $0$s), since if either side had a $+1$, we would have a higher valued subarray. Now we can pick any $1$ from this subarray and a $-1$ either from its left or right to reduce its sum by $1$, thus completing the proof. (Note that any subarray with maximum absolute sum must have at least one element with sign opposite to its sum either to its left or right.) Time complexity: $O(n)$
[ "binary search", "constructive algorithms", "data structures", "greedy" ]
2,100
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e6 + 5; int n; string s, t; int a[N]; int get(int x) { int cur = 0, mx = 0; for(int i = 1; i <= n; i++) { cur += x * a[i]; mx = max(mx, cur); if(cur < 0) cur = 0; } return mx; } int32_t main() { IOS; cin >> n >> s >> t; int sum = 0; for(int i = 1; i <= n; i++) { if(s[i - 1] != t[i - 1]) { if(s[i - 1] == '1') a[i] = -1; else a[i] = 1; } sum += a[i]; } if(sum != 0) { cout << -1; return 0; } int ans = max(get(1), get(-1)); cout << ans; return 0; }
1370
F2
The Hidden Pair (Hard Version)
\textbf{Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.} \textbf{This is an interactive problem.} You are given a tree consisting of $n$ nodes numbered with integers from $1$ to $n$. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: - Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as $s$ and $f$. In one query you can provide the set of nodes $\{a_1, a_2, \ldots, a_c\}$ of the tree. As a result, you will get two numbers $a_i$ and $dist(a_i, s) + dist(a_i, f)$. The node $a_i$ is any node from the provided set, for which the number $dist(a_i, s) + dist(a_i, f)$ is minimal. \textbf{You can ask no more than $11$ queries.}
Key Idea: We can find out one of the nodes in the path between the two hidden nodes using a single query. We can then root the tree at this node find one of the hidden nodes using binary search on its distance from the root. Solution: If we query all nodes in the tree, we will receive one of the nodes in the path between the two hidden nodes and also the distance between the two hidden nodes. Proof: Suppose the distance between the hidden nodes is equal to $l$. All the nodes in the simple path between the two hidden nodes have the sum of distances equal to $l$. For all other nodes, the sum of distances is $\gt l$. Now that we found a node $r$ in the path between the hidden nodes, we will root the tree at $r$. If we can find one of the hidden nodes, we can easily find the other hidden node by querying all nodes at distance $l$ from the first hidden node. We can find one of the hidden nodes using binary search on its distance from the root. Suppose we query all the nodes at distance $d$ from the root and receive the minimum sum of distance as $x$. If there is at least one hidden node whose distance from the root is $\ge d$, then $x$ must be equal to $l$. Otherwise, $x$ must be greater than $l$. So we can binary search on $d$ and appropriately change the upper or lower bound of the binary search based on the minimum sum of distances received for the query. This takes $10$ queries as the maximum depth could be up to $n$. Then we need one more query to find the other hidden node. This takes a total of $12$ queries. Note that this is sufficient to pass the easy version. We can further reduce the number of queries by $1$ if we notice that at least one of the hidden nodes must be at least at a distance of $\lceil{\frac{l}{2}}\rceil$ from the root. So we can set the lower bound of the binary search to $\lceil{\frac{l}{2}}\rceil$. Note that if we discard the largest child subtree of the root, it also reduces the number of queries by $1$. Time complexity: $O(n^2)$
[ "binary search", "dfs and similar", "graphs", "interactive", "shortest paths", "trees" ]
2,700
#include< bits/stdc++.h > using namespace std; const int N = 1001; vector< int > adj[N], depth(N), max_depth(N); int n, root, dist; void dfs(int i, int par){ max_depth[i] = depth[i]; for(int j : adj[i]){ if(j == par) continue; depth[j] = 1 + depth[i], dfs(j, i); max_depth[i] = max(max_depth[i], max_depth[j]); } } void find_nodes(int i, int par, int req_depth, vector< int > &nodes){ if(depth[i] == req_depth){ nodes.push_back(i); return; } for(int j : adj[i]) if(j != par && max_depth[j] <= n / 2) find_nodes(j, i, req_depth, nodes); } pair query(vector< int > nodes){ cout << "? " << nodes.size() << ' '; for(int i : nodes) cout << i << ' '; cout << endl; fflush(stdout); int x, dist; cin >> x >> dist; return {x, dist}; } int main(){ int t; cin >> t; while(t--){ cin >> n; for(int i = 1; i <= n; i++) adj[i].clear(), depth[i] = 0, max_depth[i] = 0; for(int i = 1; i < n; i++){ int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } vector< int > nodes; for(int i = 1; i <= n; i++) nodes.push_back(i); pair< int, int > res = query(nodes); root = res.first, dist = res.second; dfs(root, 0); int st = 0, en = n / 2, first_node = root; while(st <= en){ int mid = st + en >> 1; vector< int > node_set; find_nodes(root, 0, mid, node_set); if(node_set.empty()) en = mid — 1; else{ pair< int, int > res = query(node_set); if(res.second == dist) first_node = res.first, st = mid + 1; else en = mid — 1; } } vector< int > candidate_second; queue< pair< int, int > > q; vector< int > vis(n + 1); q.push({first_node, 0}); while(!q.empty()){ pair< int, int > node = q.front(); q.pop(); vis[node.first] = 1; if(node.second == dist) candidate_second.push_back(node.first); for(int j : adj[node.first]) if(!vis[j]) vis[j] = 1, q.push({j, node.second + 1}); } pair< int, int > second_node = query(candidate_second); cout << "! " << first_node << ' ' << second_node.first << endl; string correct; cin >> correct; } }
1371
A
Magical Sticks
A penguin Rocher has $n$ sticks. He has exactly one stick with length $i$ for all $1 \le i \le n$. He can connect some sticks. If he connects two sticks that have lengths $a$ and $b$, he gets one stick with length $a + b$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections. He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?
Output $\lceil \frac{n}{2} \rceil$. When $n$ is even, we can create $1+n = 2+(n-1) = 3+(n-2) = ...$ When $n$ is odd, we can create $n = 1+(n-1) = 2+(n-2) = ...$ Initially, there are only $1$ stick which has length $i (1 \le i \le n)$. If we connect $2$ sticks $s_1$ and $s_2$, after that, there is a stick which has a different length from $s_1$ and $s_2$. Then, we can create at most $1 + \lfloor \frac{n-1}{2} \rfloor$ sticks that have the same length. The value is equal to $\lceil \frac{n}{2} \rceil$. Total complexity: $O(1)$
[ "math" ]
800
#include<stdio.h> int main(){ long long n,t; scanf("%lld",&t); while(t>0){ t--; scanf("%lld",&n); if(n%2){printf("%lld\n",(n/2)+1);} else{printf("%lld\n",n/2);} } return 0; }
1371
B
Magical Calendar
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $7$ days! In detail, she can choose any integer $k$ which satisfies $1 \leq k \leq r$, and set $k$ days as the number of days in a week. Alice is going to paint some $n$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row. She wants to make \textbf{all of the painted cells to be connected by side}. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side. Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped \textbf{using only parallel moves, parallel to the calendar's sides}. For example, in the picture, a week has $4$ days and Alice paints $5$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. Alice wants to know \textbf{how many possible shapes} exists \textbf{if she set how many days a week has and choose consecutive $n$ days and paints them in calendar started in one of the days of the week}. As was said before, she considers only shapes, there all cells are connected by side.
First, let's consider in case of a week has exactly $w$ days. If $w<n$ , the length of painted cells is strictly more than one week. So there are $w$ valid shapes. (The first week contains $1,2,...,w$ days) The shapes have $w$-day width, then if the value of $w$ are different, the shapes are also different. Otherwise $(n \le w)$ , there is only one valid liner pattern. The shape is insensitive to the chosen value of $w$. We can sum up this for $1 \le w \le r$, by using following well-known formula: $a+(a+1)+(a+2)+...+b = \frac{(a+b)*(b-a+1)}{2}$ Total complexity : $O(1)$
[ "math" ]
1,200
#include<stdio.h> int main(){ long long n,l=1,r,t,res; scanf("%lld",&t); while(t>0){ t--; res=0; scanf("%lld%lld",&n,&r); if(n<=l){printf("1\n");continue;} if(n<=r){r=n-1;res=1;} printf("%lld\n",res+((l+r)*(r-l+1))/2); } return 0; }
1371
C
A Cookie for You
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $a$ vanilla cookies and $b$ chocolate cookies for the party. She invited $n$ guests of the first type and $m$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type: If there are $v$ vanilla cookies and $c$ chocolate cookies at the moment, when the guest comes, then - if the guest of the first type: if $v>c$ the guest selects a \textbf{vanilla} cookie. Otherwise, the guest selects a \textbf{chocolate} cookie. - if the guest of the second type: if $v>c$ the guest selects a \textbf{chocolate} cookie. Otherwise, the guest selects a \textbf{vanilla} cookie. After that: - If there is at least one cookie of the selected type, the guest eats one. - Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that \textbf{no one guest gets angry}. Your task is to answer her question.
If $m < \min (a,b) , n+m \le a+b$ are satisfied, the answer is "Yes". Otherwise, the answer is "No". Let's proof it. Of course, $n+m \le a+b$ must be satisfied, because violating this inequality means lack of cookies. When a type $2$ guest comes, or when $a=b$, the value of $\min(a,b)$ is decremented by $1$. You need to consider only about the case that all type $2$ guests come first and after that all type $1$ guests come, because if there is a type $1$ guest before a type $2$ guest, swapping them is better to make no one angry. (Because if there is a type $1$ guest before a type $2$ guest, the type $1$ guest have a possibility to decrease the value of $min(a,b)$ unnecessarily.) At last, all of type $1$ guests eat one cookie when there is at least one cookie(both types are ok). Total complexity: $O(1)$ UPD: $m<\min(a,b)$ is wrong, the right text is $m\le \min(a,b)$
[ "greedy", "implementation", "math" ]
1,300
#include<stdio.h> int main(){ long long t,a,b,n,m,k; scanf("%lld",&t); while(t>0){ t--; scanf("%lld%lld%lld%lld",&a,&b,&n,&m); if(a>b){k=a;a=b;b=k;} if(a<m){printf("No\n");continue;} if(a+b<n+m){printf("No\n");continue;} printf("Yes\n"); } }
1371
D
Grid-00100
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers $n,k$. Construct a grid $A$ with size $n \times n$ \textbf{consisting of integers $0$ and $1$}. The very important condition should be satisfied: the sum of all elements in the grid is exactly $k$. In other words, the number of $1$ in the grid is equal to $k$. Let's define: - $A_{i,j}$ as the integer in the $i$-th row and the $j$-th column. - $R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$ (for all $1 \le i \le n$). - $C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$ (for all $1 \le j \le n$). - In other words, $R_i$ are row sums and $C_j$ are column sums of the grid $A$. - For the grid $A$ let's define the value $f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$ (here for an integer sequence $X$ we define $\max(X)$ as the maximum value in $X$ and $\min(X)$ as the minimum value in $X$). Find any grid $A$, which satisfies the following condition. Among such grids find any, for which the value $f(A)$ is the minimum possible. Among such tables, you can find any.
We can construct a grid $A$ which has $f(A)=0$ if $k\%n=0$ , $f(A)=2(1^2+1^2)$ otherwise (the values are smallest almost obviously.) in following method: First, initialize $A_{i,j}=0$ for all $i,j$. Then, change a $0$ into $1$ $k$ times by using following pseudo code: let p=0 , q=0 for i = 1..k Change A[p+1][q+1] into 1 let p=(p+1) , q=(q+1)%n if(p==n) let p=0 , q=(q+1)%n Total complexity : $O(n^2)$
[ "constructive algorithms", "greedy", "implementation" ]
1,600
#include<stdio.h> int main(){ int n,k,t,i,j,p,q; char res[305][305]; scanf("%d",&t); while(t>0){ t--; scanf("%d%d",&n,&k); if(k%n==0){printf("0\n");} else{printf("2\n");} for(i=0;i<n;i++){ for(j=0;j<n;j++){ res[i][j]='0'; } res[i][n]=0; } p=0;q=0; while(k>0){ k--; res[p][q]='1'; p++;q++;q%=n; if(p==n){ p=0;q++;q%=n; } } for(i=0;i<n;i++){ printf("%s\n",res[i]); } } }
1371
E1
Asterism (Easy Version)
\textbf{This is the easy version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.} First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies. Yuzu is going to determine a permutation $P$. 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 (because $n=3$ but there is the number $4$ in the array). After that, she will do $n$ duels with the enemies with the following rules: - If Yuzu has \textbf{equal or more} number of candies than enemy $P_i$, she wins the duel and \textbf{gets $1$ candy}. Otherwise, she loses the duel and gets nothing. - The candy which Yuzu gets will be used in the next duels. Yuzu wants to \textbf{win all duels}. How many valid permutations $P$ exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define $f(x)$ as the number of valid permutations for the integer $x$. You are given $n$, $a$ and \textbf{a prime number} $p \le n$. Let's call a positive integer $x$ \textbf{good}, if the value $f(x)$ is \textbf{not} divisible by $p$. Find \textbf{all} good integers $x$. Your task is to solve this problem made by Akari.
Let's define $m = max(a_1,a_2,...,a_n)$. Yuzu should have at least $m-n+1$ candies initially to win all duels, then $f(x)=0$ for $x < m-n+1$. This is divisible by $p$. And if Yuzu have equal or more than $m$ candies initially, any permutation will be valid, then $f(x)=n!$ for $x \ge m$. This is divisible by $p$ , too. (because $p \le n$) Then, in this subtask, you should find whether each $f(x)$ are divisible by $p$ for $m-n+1 \le x < m$ in $O(n)$. You can find the value of $f(x)$ by following simulation: First, let $v$={the number of enemies they have strictly less than $x$ candies}, $ans=1$. Then do the following steps for $i=x,x+1,...,x+(n-1)$. $v = v$ + {the number of enemies they have exactly $i$ candies} $ans = ans * v$ $v = v - 1$ Now, $p$ is a prime. Then, "Whether $f(x)$ is divisible by $p$" is "Whether $p$ was multiplied to $ans$ as $v$ at least once." This can be simulated in $O(n)$ time for each $x$. Total complexity : $O(n^2)$
[ "binary search", "brute force", "combinatorics", "math", "number theory", "sortings" ]
1,900
#include<stdio.h> int max(int a,int b){if(a>b){return a;}return b;} int main(){ int n,p; int st,fi; int a[131072],bk[262144]={0},bas=0,i,j; int res[131072],rc=0; scanf("%d%d",&n,&p); for(i=0;i<n;i++){ scanf("%d",&a[i]); bas=max(a[i],bas); } for(i=0;i<n;i++){bk[max(0,a[i]-bas+n)]++;} for(i=1;i<262144;i++){bk[i]+=bk[i-1];} for(i=0;i<=n;i++){ for(j=0;j<n;j++){ if((bk[i+j]-j)<=0){break;} if((bk[i+j]-j)%p==0){break;} if(j==n-1){res[rc]=i+(bas-n);rc++;} } } printf("%d\n",rc); for(i=0;i<rc;i++){ if(i){printf(" ");} printf("%d",res[i]); }printf("\n"); }
1371
E2
Asterism (Hard Version)
\textbf{This is the hard version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.} First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies. Yuzu is going to determine a permutation $P$. 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 (because $n=3$ but there is the number $4$ in the array). After that, she will do $n$ duels with the enemies with the following rules: - If Yuzu has \textbf{equal or more} number of candies than enemy $P_i$, she wins the duel and \textbf{gets $1$ candy}. Otherwise, she loses the duel and gets nothing. - The candy which Yuzu gets will be used in the next duels. Yuzu wants to \textbf{win all duels}. How many valid permutations $P$ exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define $f(x)$ as the number of valid permutations for the integer $x$. You are given $n$, $a$ and \textbf{a prime number} $p \le n$. Let's call a positive integer $x$ \textbf{good}, if the value $f(x)$ is \textbf{not} divisible by $p$. Find \textbf{all} good integers $x$. Your task is to solve this problem made by Akari.
There are two different solutions to solve this problem. Solution 1: First, find the minimum $s$ which has $f(s) > 0$. You can use binary search or cumulative sum for it. Now, we can say the answers form a segment $[s,t]$ (or there are no answers). Find $t$ and proof this. Let's define $b_i$ as the number of the enemies who has equal or less than $i$ candies. Then, observe the value $C_i(x) = b_{x+i}-i \ (0 \le i \le N-1)$ : $f(x) = \prod_{i=0}^{N-1} C_i(x)$ once the value $C_i(x)$ exceed $p$ , $f(x)$ is divisible by $p$ because $C(x)$ is decremented by (at most) 1 in one step and contains some $C_i(x) = p$ in this $x$. $C_i(x) \le C_i(x+1)$ are always satisfied. Then, once $f(x)$ is divisible by $p$ , $f(x+\alpha)$ is also divisible by $p$, so $t$ can be find by using binary search. We can find $t$ without binary search by the following method:1. let $i \leftarrow 0, t \leftarrow max(A)$ 2. if($C_i(t)<p$){i++;}else{t-;} 3. Repeat the step 2. And when become $i=N$ and the algorithm stops, $t$ is the maximum value which we want. 1. let $i \leftarrow 0, t \leftarrow max(A)$ 2. if($C_i(t)<p$){i++;}else{t-;} 3. Repeat the step 2. And when become $i=N$ and the algorithm stops, $t$ is the maximum value which we want. Solution 2: We can say that $f(x) = \prod\limits_{i=x}^{x+n-1} b_i-(i-x) = \prod\limits_{i=x}^{x+n-1} x-(i-b_i)$ . We should find all $x \in \mathbb{Z}$, such that there is no $x \leq i < x + n$, such that $x \equiv i - b_i \, (\bmod p)$. It's easy to see, that there should be $max(a_i) - n \leq x \leq max(a_i)$ to have $f(x) \neq 0$ and $f(x) \neq n!$ (they are both divisible by $p$). Let's calculate $i - b_i$ for all necessary values $max(a_i) - n \leq x \leq max(a_i) + n$ and after that we can solve the problem by $O(n)$. Anyway, the total complexity is $O(n)$ or $O(n \log n)$.
[ "binary search", "combinatorics", "dp", "math", "number theory", "sortings" ]
2,300
#include<stdio.h> int max(int a,int b){if(a>b){return a;}return b;} int modp(int x,int p){ if(x>=0){return x%p;} x*=-1;x%=p; return (p-x)%p; } int main(){ int n,p; int st,fi; int a[131072],bk[262144]={0},bas=0,i; int fl[131072]={0}; int res[131072],rc=0; scanf("%d%d",&n,&p); for(i=0;i<n;i++){ scanf("%d",&a[i]); bas=max(a[i],bas); } for(i=0;i<n;i++){bk[max(0,a[i]-bas+n)]++;} for(i=1;i<262144;i++){bk[i]+=bk[i-1];} for(i=0;i<n;i++){ fl[modp((i+(bas-n))-bk[i],p)]++; } for(i=0;i<=n;i++){ if(fl[modp(i+(bas-n),p)]==0){ res[rc]=i+(bas-n); rc++; } fl[modp((i+(bas-n))-bk[i],p)]--; fl[modp(((n+i)+(bas-n))-bk[(n+i)],p)]++; } printf("%d\n",rc); for(i=0;i<rc;i++){ if(i){printf(" ");} printf("%d",res[i]); }printf("\n"); return 0; }
1371
F
Raging Thunder
You are a warrior fighting against the machine god Thor. Thor challenge you to solve the following problem: There are $n$ conveyors arranged in a line numbered with integers from $1$ to $n$ from left to right. Each conveyor has a symbol "<" or ">". The initial state of the conveyor $i$ is equal to the $i$-th character of the string $s$. There are $n+1$ holes numbered with integers from $0$ to $n$. The hole $0$ is on the left side of the conveyor $1$, and for all $i \geq 1$ the hole $i$ is on the right side of the conveyor $i$. When a ball is on the conveyor $i$, the ball moves by the next rules: If the symbol "<" is on the conveyor $i$, then: - If $i=1$, the ball falls into the hole $0$. - If the symbol "<" is on the conveyor $i-1$, the ball moves to the conveyor $i-1$. - If the symbol ">" is on the conveyor $i-1$, the ball falls into the hole $i-1$. If the symbol ">" is on the conveyor $i$, then: - If $i=n$, the ball falls into the hole $n$. - If the symbol ">" is on the conveyor $i+1$, the ball moves to the conveyor $i+1$. - If the symbol "<" is on the conveyor $i+1$, the ball falls into the hole $i$. You should answer next $q$ queries, each query is defined by the pair of integers $l, r$ ($1 \leq l \leq r \leq n$): - First, for all conveyors $l,l+1,...,r$, the symbol "<" changes to ">" and vice versa. \textbf{These changes remain for the next queries.} - After that, put \textbf{one ball} on each conveyor $l,l+1,...,r$. Then, each ball falls into some hole. Find the maximum number of balls in one hole. \textbf{After the query all balls disappear and don't considered in the next queries.}
First, observe where the balls fall. When there is a ">>>...>><<...<<<" structure, the balls on there will fall into one hole. So, our goal is handling this structure. Each query is asking about a segment. Then, to solve this problem, we can use segment tree. Each node maintains following: Prefix structure Suffix structure The answer for between above structures For example, a string "><<>><>><<>>>>" will be converted to the following data: Prefix structure : "><<" Suffix structure : ">>>>" The answer for between above structures : take the answer of ">><" or ">><<". the largest answer is $4$. And we need to implement that combining two data ( [left data] + [right data] ). Mainly we should merge left suffix and right prefix, and calculate the answer for the segment, but notice that there are some exceptions. The exceptions are in case of there are only one structure in the merged node, like ">>><<" or "<<<". (You may maintain other flags for your implement.) Then, how to handling each queries? We also keep above data for when '>' are changed into '<' and vice versa on each node of the segment tree. And when a change query actually comes to some nodes, swap these data. Apply lazy propagation for handling this. When calculate the answer for a query, don't forget to consider about the prefix(or the suffix). Total complexity : $O(n + q \log n)$
[ "data structures", "divide and conquer", "implementation" ]
2,800
#include<stdio.h> #include<stdbool.h> #define ssize 1048576 int max(int a,int b){if(a>b){return a;}return b;} typedef struct{ //str[0] = prefix //str[1] = suffix //str[][0] = >>>> //str[][1] = <<<< int str[2][2]; int res; int dvd; }stnode; stnode stree[2*ssize][2],vd; int fl[2*ssize]; void stnpr(stnode x,int br){ printf("<%d %d %d %d %d : %d>",x.str[0][0],x.str[0][1],x.str[1][0],x.str[1][1],x.dvd,x.res); if(br){printf("\n");} } stnode merge(stnode l,stnode r){ stnode res; //stnpr(l,0);printf("+");stnpr(r,1); res.res=max(l.res,r.res); if(l.dvd==1&&r.dvd==1){ res.str[0][0]=l.str[0][0]; res.str[0][1]=l.str[0][1]; if(l.str[1][1]!=0 && r.str[0][0]!=0){ res.res=max(max(l.str[1][0]+l.str[1][1],r.str[0][0]+r.str[0][1]),res.res); } else{ res.res=max(l.str[1][0]+l.str[1][1]+r.str[0][0]+r.str[0][1],res.res); } res.str[1][0]=r.str[1][0]; res.str[1][1]=r.str[1][1]; res.dvd=1; } else if(l.dvd==1&&r.dvd==0){ res.str[0][0]=l.str[0][0]; res.str[0][1]=l.str[0][1]; if(l.str[1][1]!=0 && r.str[0][0]!=0){ res.res=max(l.str[1][0]+l.str[1][1],res.res); res.str[1][0]=r.str[0][0]; res.str[1][1]=r.str[0][1]; } else{ res.str[1][0]=l.str[1][0]+r.str[0][0]; res.str[1][1]=l.str[1][1]+r.str[0][1]; } res.dvd=1; } else if(l.dvd==0&&r.dvd==1){ if(l.str[0][1]!=0 && r.str[0][0]!=0){ res.res=max(r.str[0][0]+r.str[0][1],res.res); res.str[0][0]=l.str[0][0]; res.str[0][1]=l.str[0][1]; } else{ res.str[0][0]=l.str[0][0]+r.str[0][0]; res.str[0][1]=l.str[0][1]+r.str[0][1]; } res.str[1][0]=r.str[1][0]; res.str[1][1]=r.str[1][1]; res.dvd=1; } else{ if(l.str[0][1]!=0&&r.str[0][0]!=0){ res.str[0][0]=l.str[0][0]; res.str[0][1]=l.str[0][1]; res.str[1][0]=r.str[0][0]; res.str[1][1]=r.str[0][1]; res.dvd=1; } else{ res.str[0][0]=l.str[0][0]+r.str[0][0]; res.str[0][1]=l.str[0][1]+r.str[0][1]; res.str[1][0]=0; res.str[1][1]=0; res.dvd=0; } } //stnpr(res,1); return res; } void stinit(){ int i; for(i=(ssize-2);i>=0;i--){ stree[i][0]=merge(stree[i*2+1][0],stree[i*2+2][0]); stree[i][1]=merge(stree[i*2+1][1],stree[i*2+2][1]); } for(i=0;i<2*ssize;i++){ fl[i]=0; } } void eval(int k){ if(fl[k]%2==1){ //printf("rev %d\n",k); stnode c; c=stree[k][0]; stree[k][0]=stree[k][1]; stree[k][1]=c; if(k<(ssize-1)){ fl[k*2+1]++; fl[k*2+2]++; } } fl[k]=0; } void revquery(int a,int b,int k,int l,int r){ eval(k); if(r<=a || b<=l){return;} if(a<=l && r<=b){ fl[k]++; eval(k); return; } else{ eval(k*2+1); eval(k*2+2); revquery(a,b,k*2+1,l,(l+r)/2); revquery(a,b,k*2+2,(l+r)/2,r); stree[k][0]=merge(stree[k*2+1][0],stree[k*2+2][0]); stree[k][1]=merge(stree[k*2+1][1],stree[k*2+2][1]); fl[k]=0; } } stnode getquery(int a,int b,int k,int l,int r){ //printf("call %d : [%d , %d) vs [%d , %d)\n",k,l,r,a,b); eval(k); if(r<=a || b<=l){return vd;} if(a<=l && r<=b){ //printf("%d back:<%d %d %d %d %d : %d>\n",k,stree[k][0].str[0][0],stree[k][0].str[0][1],stree[k][0].str[1][0],stree[k][0].str[1][1],stree[k][0].dvd,stree[k][0].res); return stree[k][0]; } stnode ld,rd; ld=getquery(a,b,k*2+1,l,(l+r)/2); rd=getquery(a,b,k*2+2,(l+r)/2,r); //printf("%d l:<%d %d %d %d %d : %d>\n",k,ld.str[0][0],ld.str[0][1],ld.str[1][0],ld.str[1][1],ld.dvd,ld.res); //printf("%d r:<%d %d %d %d %d : %d>\n",k,rd.str[0][0],rd.str[0][1],rd.str[1][0],rd.str[1][1],rd.dvd,rd.res); return merge(ld,rd); } int main(){ vd.str[0][0]=0;vd.str[0][1]=0; vd.str[1][0]=0;vd.str[1][1]=0; vd.res=0;vd.dvd=0; stnode tl,tr; tl.str[0][0]=0;tl.str[0][1]=1; tl.str[1][0]=0;tl.str[1][1]=0; tl.res=0;tl.dvd=0; tr.str[0][0]=1;tr.str[0][1]=0; tr.str[1][0]=0;tr.str[1][1]=0; tr.res=0;tr.dvd=0; int n,q,i; int l,r,ans; stnode res; char s[ssize]; scanf("%d%d%s",&n,&q,&s[1]); for(i=0;i<2*ssize;i++){ stree[i][0]=vd; stree[i][1]=vd; } for(i=1;i<=n;i++){ if(s[i]=='<'){ stree[i+(ssize-1)][0]=tl; stree[i+(ssize-1)][1]=tr; } else{ stree[i+(ssize-1)][0]=tr; stree[i+(ssize-1)][1]=tl; } } stinit(); while(q>0){ q--; scanf("%d%d",&l,&r); revquery(l,r+1,0,0,ssize); res=getquery(l,r+1,0,0,ssize); //stnpr(res,1); ans=max(res.str[0][0]+res.str[0][1],res.str[1][0]+res.str[1][1]); ans=max(res.res,ans); printf("%d\n",ans); } return 0; }
1372
A
Omkar and Completion
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array $a$ of length $n$ is called \textbf{complete} if all elements are positive and don't exceed $1000$, and for all indices $x$,$y$,$z$ ($1 \leq x,y,z \leq n$), $a_{x}+a_{y} \neq a_{z}$ (not necessarily distinct). You are given one integer $n$. Please find any \textbf{complete} array of length $n$. It is guaranteed that under given constraints such array exists.
Notice that since all elements must be positive, $k \neq 2k$. The most simple construction of this problem is to simply make all elements equal to $1$.
[ "constructive algorithms", "implementation" ]
800
import java.util.* fun main() { val jin = Scanner(System.`in`) for (c in 1..jin.nextInt()) { val n = jin.nextInt() for (j in 1..n) { print("1 ") } println() } }
1372
B
Omkar and Last Class of Math
In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$. Omkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive integers $a$ and $b$ such that $a + b = n$ and $LCM(a, b)$ is the minimum value possible. Can you help Omkar solve his ludicrously challenging math problem?
Short Solution: The two integers are $k$ and $n-k$, where $k$ is the largest proper factor of $n$. Proof: Let the two integers be $k$ and $n-k$. Assume WLOG that $k \leq n-k$. Notice that this implies that $n - k \geq \frac n 2$. We first claim that $LCM(k, n-k) = n-k < n$ if $k \mid n$, and we prove this as follows: if $k \mid n$, then there exists some integer $m$ such that $m \cdot k = n$. The integer $n-k$ can then be written as $(m-1) \cdot k$, which is a multiple of $k$. Thus, $LCM(k, n-k) = n-k$ if $k \mid n$. We now show that $LCM(k, n-k) \geq n$ if $k \nmid n$. We show this by using the fact that $LCM(a, b) = b$ iff $a \mid b$, so if $k \nmid n$, $k \nmid n - k$, and so $LCM(k, n-k) \neq n-k$. And since $LCM(k, n - k)$ must be a multiple of both $k$ and $n - k$, it follows that $LCM(k, n-k) \geq 2 \cdot (n-k) \geq 2 \cdot \frac n 2 = n$. We have now established that to minimize $LCM(k, n-k)$, $k$ must be a factor of $n$. And, since $LCM(k, n-k) = n-k$ when $k$ is a factor of $n$, we need to minimize $n-k$, so we must maximize $k$ by choosing it to be the largest proper factor of $n$ (i. e. the largest factor of $n$ other than $n$). We then simply need to find $k$, the largest proper factor of $n$. If $p$ is the smallest prime dividing $n$, then $k = \frac n p$, so it suffices to find the smallest prime factor of $n$. We can do this by simply checking all values of $p$ such that $2 \leq p \leq \sqrt n$. If $n$ is not prime, then it must have a prime factor not exceeding $\sqrt{n}$. Furthermore, if we do not find a factor of $n$ between $2$ and $\sqrt n$, then $n$ must be prime so we simply get $p = n$ and $k = \frac n p = 1$. We're given that $n \leq 10^9$, so $\sqrt n \leq 10^{\frac 9 2} < 10^5$. $t \leq 10$, meaning that we will check less than $10^6$ numbers, which runs well under the time limit.
[ "greedy", "math", "number theory" ]
1,300
fun main() { for (c in 1..readLine()!!.toInt()) { val n = readLine()!!.toInt() var p = 0 for (m in 2..100000) { if (n % m == 0) { p = m break } } if (p == 0) { p = n } println("${n / p} ${n - (n / p)}") } }
1372
C
Omkar and Baseball
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position. Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$. An array $a$ is a subarray of an array $b$ if $a$ 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.
You need at most $2$ special exchanges to sort the permutation. Obviously, $0$ special exchanges are needed if the array is already sorted. Let's look into cases in which you need $1$ special exchange to sort the array. Refer to i as a matching index if $a_i = i$. If there are no matching indices, then you can just use one special exchange to sort the entire thing. Otherwise, you can use the location of matching indices to determine whether you need more than $1$ special exchange. If all matching indices are located in some prefix of the permutation, you can sort the permutation with one special exchange. The same is true for a suffix. In other words, if you can choose a subarray in the permutation such that all elements contained in the subarray are NOT matching and the elements outside of this subarray are matching, then one special exchange is needed to sort the array. Otherwise, you need $2$ special exchanges to sort the permutation. Let's prove why you do not need more than $2$ special exchanges. You can quickly check that you need at most $2$ special exchanges for all permutations of length $\leq 3$. For permutations of length $\geq 4$, I claim that we can perform $2$ special exchanges on the whole array; to show this it suffices to construct a permutation $p$ that has no matching indices with either the given permutation or the identity permutation $1, 2, \ldots, n$. We can do this as follows: For simplicity, assume that $n$ is even. We will assign the numbers $\frac n 2 + 1, \frac n 2 + 2, \ldots, n$ to the first $\frac n 2$ positions of our permutation $p$ and the numbers $1, 2, \ldots, \frac n 2$ to the last $\frac n 2$ positions of $p$. This ensures that $p$ has no matching indices with the identity permutation. Then, for all integers $b$ such that their position $i$ in $a$ (i. e. the $j$ such that $a_j = b$) is in the appropriate half of $p$, assign $p_i = b$; assign other $b$ to arbitrary positions in the appropriate half of $p$. Finally, cyclically rotate each half of $p$ - this ensures that $p$ has no matching indices with $a$. As an example, let's take $a = [3, 6, 2, 4, 5, 1]$. You can quickly check that this cannot be done in less than $2$ special exchanges. The construction of $p$ goes as follows: First, we move all numbers to the proper half of $p$, so that $p = [4, 5, 6, 1, 2, 3]$. Observing that $a_2 = 6$ and $a_6 = 1$, we set $p_2 = 6$ and $p_6 = 1$ then replace the remaining elements arbitrarily into the correct half, so we can get, for example, $p = [4, 6, 5, 2, 3, 1]$. Finally, we cyclically rotate each half of $p$, obtaining $p = [5, 4, 6, 1, 2, 3]$, which has no matching indexes with either $a = [3, 6, 2, 4, 5, 1]$ or $[1, 2, 3, 4, 5, 6]$. This can be extended to odd $n$ by first choosing some element other than $1$ and $a_1$ to be $p_1$ (this works for $n \geq 3$ and we must have $n \geq 5$ anyway in this case), and then running the same algorithm on the rest of $p$.
[ "constructive algorithms", "math" ]
1,500
import java.io.BufferedReader import java.io.InputStreamReader fun main() { val jin = BufferedReader(InputStreamReader(System.`in`)) for (c in 1..jin.readLine().toInt()) { val n = jin.readLine().toInt() val scores = jin.readLine().split(" ").map { it.toInt() - 1 } if ((1 until n).all { scores[it - 1] < scores[it] }) { println(0) } else { var stage = 0 var answer = 1 for (j in 0 until n) { if (scores[j] == j) { if (stage == 1) { stage = 2 } } else { if (stage == 0) { stage = 1 } else if (stage == 2) { answer = 2 break } } } println(answer) } } }
1372
D
Omkar and Circle
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given $n$ nonnegative integers $a_1, a_2, \dots, a_n$ arranged in a circle, where $n$ must be odd (ie. $n-1$ is divisible by $2$). Formally, for all $i$ such that $2 \leq i \leq n$, the elements $a_{i - 1}$ and $a_i$ are considered to be adjacent, and $a_n$ and $a_1$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value. Help Danny find the maximum possible circular value after some sequences of operations.
First note that any possible circular value consists of the sum of some $(n+1)/2$ elements. Now let's think about how these $(n+1)/2$ values would look like in the circle. Let's consider any one move on index $i$. $a_i$ will be replaced with the sum of $a_{i-1}$ and $a_{i+1}$ (wrap around to index $1$ or $n$ if needed). Then let's consider making a move on $i+2$, since it will be adjacent to $i$ after the first move. Then its value will become $a_{i-1}+a_{i+1}+a_{i+3}$. This implies that alternating values play a role in the construction of the $(n+1)/2$ values contained in the final circular value. Now let's consider the final move when there's $3$ elements left in the circle. This is the only move that takes the sum of two adjacent elements in the initial circle. With this observation, we can achieve our final construction as follows: Choose any $(n+1)/2$ elements in the initial circle such that exactly one pair of chosen numbers are adjacent to each other. The answer will be the maximum of the circular value over all possible constructions. While there are ways involving complicated prefix sums/segment trees, the cleanest implementation is as follows: create an array whose values consists of $[a_1, a_3, ..., a_n, a_2, a_4, ..., a_{n-1}]$. Append this new array to itself to account for the circular structure. Now all you simply have to do is to find the maximum sum over all subarrays of length $(n+1)/2$. This can be done with sliding window in $O(n)$ time.
[ "brute force", "dp", "games", "greedy" ]
2,100
import kotlin.math.max fun main() { val n = readLine()!!.toInt() val m = (n + 1) / 2 val array = readLine()!!.split(" ").map { it.toLong() } var curr = 0L for (j in 0 until m) { curr += array[2 * j] } var answer = curr for (j in 0..n - 2) { curr -= array[(2 * j) % n] curr += array[(2 * (j + m)) % n] answer = max(answer, curr) } println(answer) }
1372
E
Omkar and Last Floor
Omkar is building a house. He wants to decide how to make the floor plan for the last floor. Omkar's floor starts out as $n$ rows of $m$ zeros ($1 \le n,m \le 100$). Every row is divided into intervals such that every $0$ in the row is in exactly $1$ interval. For every interval for every row, Omkar can change exactly one of the $0$s contained in that interval to a $1$. Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the $i$-th column is $q_i$, then the quality of the floor is $\sum_{i = 1}^m q_i^2$. Help Omkar find the maximum quality that the floor can have.
Let $dp_{l,r}$ be the answer for the columns from $l$ to $r$. To solve $dp_{l,r}$, it is optimal to always fill some column within $l$ to $r$ to the max. Let's call this column $k$. The transition is thus $dp_{l,k-1} + ($ number of intervals that are fully within $l$ and $r$ and include $k)^2 + dp_{k+1,r}$. For every $dp_{l,r}$ loop through all possible columns to be $k$ and take the max. The answer is $dp_{1,m}$. The efficiency is $O(N \cdot M^3)$. There are $M^2$ dp states. For every state, you transition based on $M$ cases of $k$, and it takes $O(N)$ to determine how much the max column contributes. Proof: Consider an optimal arrangement and the column with the most 1's in that arrangement. If there is an interval intersecting that column whose 1 isn't in that column, then moving the 1 to that column would not decrease (and possibly would increase) the quality of that arrangement. Thus, it's optimal for the column with the most 1s to have all the possible 1s that it can have.
[ "dp", "greedy", "two pointers" ]
2,900
import java.io.BufferedReader import java.io.InputStreamReader import kotlin.math.max fun main() { val jin = BufferedReader(InputStreamReader(System.`in`)) val (n, m) = jin.readLine().split(" ").map { it.toInt() } val left = Array(n + 1) { IntArray(m + 1) } val right = Array(n + 1) { IntArray(m + 1) } for (y in 1..n) { val k = jin.readLine().toInt() for (j in 1..k) { val (l, r) = jin.readLine().split(" ").map { it.toInt() } for (x in l..r) { left[y][x] = l right[y][x] = r } } } val dp = Array(m + 2) { IntArray(m + 2) } for (l in m downTo 1) { for (r in l..m) { for (x in l..r) { var amt = 0 for (y in 1..n) { if (left[y][x] >= l && right[y][x] <= r) { amt++ } } dp[l][r] = max(dp[l][r], dp[l][x - 1] + (amt * amt) + dp[x + 1][r]) } } } println(dp[1][m]) }
1372
F
Omkar and Modes
Ray lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities: - The array has $n$ ($1 \le n \le 2 \cdot 10^5$) elements. - Every element in the array $a_i$ is an integer in the range $1 \le a_i \le 10^9.$ - The array is sorted in nondecreasing order. Ray is allowed to send Omkar a series of queries. A query consists of two integers, $l$ and $r$ such that $1 \le l \le r \le n$. Omkar will respond with two integers, $x$ and $f$. $x$ is the mode of the subarray from index $l$ to index $r$ inclusive. The mode of an array is defined by the number that appears the most frequently. If there are multiple numbers that appear the most number of times, the smallest such number is considered to be the mode. $f$ is the amount of times that $x$ appears in the queried subarray. The array has $k$ ($1 \le k \le \min(25000,n)$) distinct elements. However, due to Ray's sins, Omkar will not tell Ray what $k$ is. Ray is allowed to send at most $4k$ queries. Help Ray find his lost array.
For both solutions, we must first make the critical observation that because the array is sorted, all occurrences of a value $x$ occur as a single contiguous block. Solution 1 We will define a recursive function $determine(l, r)$ which will use queries to determine the array. We will also store an auxiliary list of previously returned query values $(x, f)$ - not the queries themselves, but only the values returned, so that we know that if $(x, f)$ is in the list then some previous query revealed that there were $f$ instances of $x$ in some query, and that we haven't already determined exactly where in the array those $f$ instances of $x$ are. The execution of $determine(l, r)$ will proceed as follows: first, query the interval $[l, r]$, and let the result be $(x_1, f_1)$. If there exists some previous query result $(x_1, f_2)$ in our auxiliary list, then we will guarantee by details yet to be explained of $determine(l, r)$ that the interval that produced that result contained $[l, r]$ and that no part of those $f_2$ occurrences of $x_1$ occurred to the left of $[l, r]$. This allows us to exactly determine the location of those $f_2$ occurrences of $x_1$. We mark these occurrences in our answer, and then remove $(x_1, f_2)$ from our auxiliary list and do not add $(x_1, f_1)$. If $[l, r]$ is not entirely composed of occurrences of $x_1$, then the remaineder of the interval must be $[l, r']$ for some $r'$, and in that case we then call $determine(l, r')$. If there does not exist some previous query result $(x_1, f_2)$ in our auxiliary list, then we add $(x_1, f_1)$ to the list and do as follows: while the exact locations of those $f_1$ occurrences of $x_1$ have not been determined, call $determine(l', l' + f_1 - 1)$, where $l'$ is the leftmost index in $[l, r]$ which has not yet been determined. Once those locations have been determined, call $determine(l', r)$. To determine the entire array we simply call $determine(1, n)$. It is clear that this will correctly determine the array. We can see that it uses at most $4k$ queries as follows: for each block of integers of the same value represented by a query result $(x, f)$ that we add to our auxiliary list, we use $2$ queries to determine the exact location of those integers: one when added $(x, f)$ to the list, and one when removing $(x, f)$ from the list. This does not guarantee that the algorithm uses $2k$ queries because some calls of $determine$ can split a block of integers of the same value into two blocks. However, we can show that any blocks formed by splitting a single block into two cannot be further split as they occur either at the beginning or end of a queried interval (the full proof is left as an exercise to the reader), so each distinct value in the array will produce at most $2$ blocks, each of which will be determined in $2$ queries, meaning that the algorithm uses at most $4k$ queries. Side note: you can in fact further show that the algorithm always uses at most $4k - 4$ queries and that there exists an array for all $k \geq 2$ which forces the algorithm to use $4k - 4$ queries. Solution 2 Again, we will define a recursive function $determine(l, r)$, but this time we will only additionally maintain the currently known values in the answer. The execution of $determine(l, r)$ will proceed as follows: first, query the interval $[l, r]$ and let the result be $(x, f)$. Then, find the largest integer $k$ such that $2^k \leq f$ and then for all $j$ in $[l, r]$ that are multiples of $2^k$, determine the value located at index $j$, either by querying $[j, j]$ or by using already known values. By the definition of $k$, there will be either one or two such indexes $j$ such that the values at those indexes are equal to $x$. If there is only one such index, let this index be $j_1$. Make two queries $[j_1 - 2^k + 1, j_1]$ and $[j_1, j_1 + 2^k - 1]$ and let the results of these queries be $(x_1, f_1)$ and $(x_2, f_2)$ respectively. We can show that at least one of $x_1$ and $x_2$ must be equal to $x$. If $x_1 = x$, then we see that the $f$ occurrences of $x$ must be precisely the interval $[j_1 - f_1 + 1, j_1 - f_1 + f]$. If $x_2 = x$, then we see that the $f$ occurrences of $x$ must be precisely the interval $[j_1 + f_2 - f, j_1 + f_2 - 1]$. If there are two such indexes, let these indexes be $j_1$ and $j_2$ so that $j_1 < j_2$. Note that it must be true that $j_1 + 2^k = j_2$. Make a single query $[j_1 - 2^k + 1, j_2]$ and let the result be $(x_1, f_1)$. We can show that $x_1$ must be equal to $x$, so we can then conclude that the $f$ occurrences fo $x$ must be precisely the interval $[j_2 - f_1 + 1, j_2 - f_1 + f]$. After the interval containing the $f$ occurrences of $x$ has been determined, mark these occurrences in our answer and then call $determine$ on the remaining not-fully-determined interval to the left if it exists and the remaining not-fully-determined interval to the right if it exists. To determine the entire array we simply call $determine(1, n)$. It is clear that this will correctly determine the array. We can see that it uses at most $4k$ queries as follows: Each call to $determine$ finds all occurrences of a distinct value $x$. We will refer to the queries of single indexes $j$ that were multiples of some $2^k$ as $j$-queries. For each $x$, we perform the following queries other than $j$-queries: the first query in $determine$, and then either two additional queries if only one $j$-query was found to equal $x$, or a single additional query if two $j$-queries were found to equal $x$. This means that if we group each $j$-query with the value $x$ that it equaled, then we will have performed exactly $4$ queries for each $x$, and so the algorithm must therefore use exactly $4k$ queries.
[ "binary search", "divide and conquer", "interactive" ]
2,700
import kotlin.math.max import kotlin.math.min fun main() { val n = readLine()!!.toInt() val answer = IntArray(n + 1) val occurrences = mutableMapOf<Int, MutableList<Int>>() fun query(l: Int, r: Int): Pair<Int, Int> { println("? $l $r") val line = readLine()!!.split(" ") return Pair(line[0].toInt(), line[1].toInt()) } fun calc(l: Int, r: Int, ePrev: Int) { if (l > r) { return } var q = query(l, r) val x = q.first val f = q.second var e = ePrev while (1 shl e > f) { e-- } if (e < ePrev) { var j = l - (l % (1 shl e)) if (j < l) { j += 1 shl e } while (j <= r) { if (j % (1 shl ePrev) != 0) { q = query(j, j) occurrences.computeIfAbsent(q.first) { mutableListOf() }.add(j) } j += 1 shl e } } val ixs = occurrences[x]!! var leftBound = 0 if (ixs.size == 1) { q = query(max(l, ixs[0] - (1 shl e) + 1), ixs[0]) if (q.first == x) { leftBound = ixs[0] - q.second + 1 } else { q = query(ixs[0], min(r, ixs[0] + (1 shl e) - 1)) leftBound = ixs[0] + q.second - f } } else { q = query(max(l, ixs.min()!! - (1 shl e) + 1), ixs.max()!!) leftBound = ixs.max()!! - q.second + 1 } for (j in leftBound until leftBound + f) { answer[j] = x } calc(l, leftBound - 1, e) calc(leftBound + f, r, e) } calc(1, n, 20) println('!' + answer.joinToString(" ").substring(1)) }
1373
A
Donut Shops
There are two rival donut shops. The first shop sells donuts at retail: each donut costs $a$ dollars. The second shop sells donuts only in bulk: box of $b$ donuts costs $c$ dollars. So if you want to buy $x$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $x$. You want to determine two \textbf{positive integer} values: - how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop? - how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to $-1$. If there are multiple possible answers, then print any of them. \textbf{The printed values should be less or equal to $10^9$. It can be shown that under the given constraints such values always exist if any values exist at all.}
At first notice that if there exists a value for the second shop, then the value divisible by $b$ also exists. For any $x$ you can round it up to the nearest multiple of $b$. That won't change the price for the second shop and only increase the price for the first shop. You can also guess that if there exists a value for the first shop, then the value with $1$ modulo $b$ also exists (exactly $1$ donut on top of some number of full boxes). Following the same logic - the second shop needs an entire new box and the first shop needs only an extra donut. So let's take a look at the smallest values of two kinds: $x = b$: this value is valid for the second shop if one box is cheaper than $b$ donuts in the first shop. Otherwise, no matter how many boxes will you take, they will never be cheaper than the corresponding number of donuts. $x = 1$: this value is valid for the first shop if one donut is cheaper than one box in the second shop. Apply the same idea - otherwise no value for the first shop is valid. Overall complexity: $O(1)$ per testcase.
[ "greedy", "implementation", "math" ]
1,000
for tc in range(int(input())): a, b, c = map(int, input().split()) print(1 if a < c else -1, end=" ") print(b if c < a * b else -1)
1373
B
01 Game
Alica and Bob are playing a game. Initially they have a binary string $s$ consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two \textbf{different adjacent} characters of string $s$ and delete them. For example, if $s = 1011001$ then the following moves are possible: - delete $s_1$ and $s_2$: $\textbf{10}11001 \rightarrow 11001$; - delete $s_2$ and $s_3$: $1\textbf{01}1001 \rightarrow 11001$; - delete $s_4$ and $s_5$: $101\textbf{10}01 \rightarrow 10101$; - delete $s_6$ and $s_7$: $10110\textbf{01} \rightarrow 10110$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.
If there is at least one character 0 and at least one character 1, then current player can always make a move. After the move the number of character 0 decreases by one, and the number of character 1 decreases by one too. So the number of moves is always $min(c0, c1)$, where $c0$ is the number of characters 0 in string $s$, and $c1$ is the number of characters 1 in string $s$. So if $min(c0, c1)$ is odd then Alice wins, otherwise Bob wins.
[ "games" ]
900
for _ in range(int(input())): s = input() print('DA' if min(s.count('0'), s.count('1')) % 2 == 1 else 'NET')
1373
C
Pluses and Minuses
You are given a string $s$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: \begin{verbatim} res = 0 for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur < 0 ok = false break if ok break \end{verbatim} Note that the $inf$ denotes infinity, and the characters of the string are numbered from $1$ to $|s|$. You have to calculate the value of the $res$ after the process ends.
Let's replace all + with 1, and all - with -1. After that let's create a preffix-sum array $p$ ($p_i = \sum\limits_{j=1}^{i} s_j$). Also lets create array $f$ such that $f_i$ is equal minimum index $j$ such that $p_j = -i$ (if there is no such index $p_i = -1$). Let's consider the first iteration of loop $for ~ init ~ = ~ 0 ~ to ~ inf$. If $f_1 = -1$ then process ends and $res = |s|$. Otherwise the condition $if ~ cur ~ < ~ 0$ fulfilled then the value of $i$ will be equal to $f_1$. So, the value of $res$ is equal to $f_1$ after first iteration. Now, let's consider the second iteration of loop $for ~ init ~ = ~ 0 ~ to ~ inf$. If $f_2 = -1$ then process ends and $res = f_1 + |s|$. Otherwise the condition $if ~ cur ~ < ~ 0$ fulfilled then the value of $i$ will be equal to $f_2$. So, the value of $res$ is equal to $f_1 + f_2$ after second iteration. In this way we can calculate the value of $res$ after the process ends.
[ "math" ]
1,300
for _ in range(int(input())): s = input() cur, mn, res = 0, 0, len(s) for i in range(len(s)): cur += 1 if s[i] == '+' else -1 if cur < mn: mn = cur res += i + 1 print(res)
1373
D
Maximum Sum on Even Positions
You are given an array $a$ consisting of $n$ integers. Indices of the array start from zero (i. e. the first element is $a_0$, the second one is $a_1$, and so on). You can reverse \textbf{at most one} subarray (continuous subsegment) of this array. Recall that the subarray of $a$ with borders $l$ and $r$ is $a[l; r] = a_l, a_{l + 1}, \dots, a_{r}$. Your task is to reverse such a subarray that the sum of elements on \textbf{even} positions of the resulting array is \textbf{maximized} (i. e. the sum of elements $a_0, a_2, \dots, a_{2k}$ for integer $k = \lfloor\frac{n-1}{2}\rfloor$ should be maximum possible). You have to answer $t$ independent test cases.
Firstly, we can notice that the reverse of of odd length subarray does nothing because it doesn't change parities of indices of affected elements. Secondly, we can consider the reverse of the subarray of length $2x$ as $x$ reverses of subarrays of length $2$ (i.e. it doesn't matter for us how exactly the subarray will be reversed, we can only consider changing parities). Now, there are two ways: the first one is smart and the second one is dynamic programming. Consider the first way. Calculate the initial sum of elements on even positions $sum$. Then let's create two arrays $v_1$ and $v_2$. There $v_1[i]$ is $a[2i+1] - a[2i]$ for all $i$ from $0$ to $\lfloor\frac{n}{2}\rfloor - 1$ and $v_2[i]$ is $a[2i] - a[2i+1]$ for all $i$ from $0$ to $\lfloor\frac{n}{2}\rfloor - 1$. Elements of the first array deonte the profit if we reverse the subarray tarting from the even position, and elemnts of the second array denote the profit if we reverse the subarray starting from the odd position. Now we need to find the subarray with the maximum sum in both arrays (this will maximize overall profit) and add this value to $sum$ to get the answer. This problem can be solved easily: consider the sum of the subarray $[l; r]$ as the difference of two prefix sums $pref_{r} - pref_{l-1}$. To maximize it, consider all right borders and minimize the value $pref_{l-1}$. Iterate over all positions of the array, maintaining the current prefix sum $csum$ and the minimum prefix sum we meet $msum$. Update $csum := csum + a_i$, then update $msum := min(msum, csum)$ and then update the answer with the value $csum - msum$. And the second way is author's solution and it is dynamic programming. This idea can be transformed to solve such problems in which you need to apply some function to some small number of subsegments (of course, under some constraints on functions). State of our dynamic programming is $dp_{i, j}$ where $i \in [0; n]$ and $j \in [0; 2]$. $dp_{i, 0}$ denotes the answer on the prefix of length $i$ if we didn't start reversing the subarray, $dp_{i, 1}$ denotes the answer if we started reversing the subarray but didn't end it and $dp_{i, 2}$ denotes the answer if we ended reversing the subarray. Transitions are pretty easy: $dp_{i + 1, 0} = max(dp_{i + 1, 0}, dp_{i, 0} + [i \% 2 == 0? a_i : 0])$; $dp_{i + 2, 1} = max(dp_{i + 2, 1}, max(dp_{i, 0}, dp_{i, 1}) + [i \% 2 == 0 ? a_{i + 1} : a_i])$; $dp_{i + 1, 2} = max(dp_{i + 1, 2}, max(dp_{i, 0}, dp_{i, 1}, dp_{i, 2}) + [i \% 2 == 0? a_i : 0])$. The value $x ? y : z$ is just a ternary if statement. If $x$ is true then return $y$ otherwise return $z$. The answer is $max(dp_{n, 0}, dp_{n, 1}, dp_{n, 2})$. Time complexity with both approaches is $O(n)$.
[ "divide and conquer", "dp", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto &it : a) cin >> it; vector<vector<long long>> dp(n + 1, vector<long long>(3)); for (int i = 0; i < n; ++i) { dp[i + 1][0] = max(dp[i + 1][0], dp[i][0] + (i & 1 ? 0 : a[i])); if (i + 2 <= n) dp[i + 2][1] = max(dp[i + 2][1], max(dp[i][0], dp[i][1]) + (i & 1 ? a[i] : a[i + 1])); dp[i + 1][2] = max(dp[i + 1][2], max({dp[i][0], dp[i][1], dp[i][2]}) + (i & 1 ? 0 : a[i])); } cout << max({dp[n][0], dp[n][1], dp[n][2]}) << endl; } return 0; }
1373
E
Sum of Digits
Let $f(x)$ be the sum of digits of a decimal number $x$. Find the smallest non-negative integer $x$ such that $f(x) + f(x + 1) + \dots + f(x + k) = n$.
There are many ways to solve this problem (including precalculating all answers), but the model solution is based on the following: In most cases, $f(x + 1) = f(x) + 1$. It is not true only when the last digit of $x$ is $9$ (and if we know the number of $9$-digits at the end of $x$, we can easily derive the formula for $f(x + 1)$). And since $k \le 9$, there will be at most one number with last digit equal to $9$ in $[x, x + 1, \dots, x + k]$. Let's iterate on the last digit of $x$ and the number of $9$-digits before it. Suppose the fixed $x$ has no other digits other than the last one and several $9$-digits before it. Let's calculate $s = f(x) + f(x + 1) + f(x + 2) \dots + f(x + k)$. Here goes the trick. If we prepend $x$ with several digits such that the last of them is not $9$, and the sum of those digits is $d$, then $f(x) + f(x + 1) + f(x + 2) \dots + f(x + k) = s + d(k + 1)$. So we can easily derive the value of $d$ we need and construct the smallest number with sum of digits equal to $d$ (don't forget that the last digit should not be $9$).
[ "brute force", "constructive algorithms", "dp", "greedy" ]
2,200
def get(s): return str(s % 9) + '9' * (s // 9) for tc in range(int(input())): n, k = map(int, input().split()) k += 1 bst = 10**100 for d in range(10): ends = 0 for i in range(k): ends += (d + i) % 10 if ends > n: continue if d + k > 10: for cnt in range(12): s = 9 * cnt * (10 - d) if s > n - ends: break for nd in range(9): ns = s + (10 - d) * nd + (k - (10 - d)) * (nd + 1) if ns > n - ends: break if (n - ends - ns) % k == 0: bst = min(bst, int(get((n - ends - ns) // k) + str(nd) + '9' * cnt + str(d))) elif (n - ends) % k == 0: bst = min(bst, int(get((n - ends) // k) + str(d))) print(-1 if bst == 10**100 else bst)
1373
F
Network Coverage
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and $n$ cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the $i$-th city contains $a_i$ households that require a connection. The government designed a plan to build $n$ network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the $i$-th network station will provide service only for the $i$-th and the $(i + 1)$-th city (the $n$-th station is connected to the $n$-th and the $1$-st city). All network stations have capacities: the $i$-th station can provide the connection to at most $b_i$ households. Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station $i$ provides the connection to at most $b_i$ households.
There are plenty of different solutions to this problem. Here is one that doesn't use Hall's theorem. Let's look at pair $(a_i, b_i)$ as fuction $f_i(in) = out$: how many connections $out$ will be left for the $(i + 1)$-th city if we take $in$ connections from the $(i - 1)$-th station. This function has the following structure: there is a minimum required $in$ (let's name it $minx_i$) to meet the needs of the $i$-th city and with $minx_i$ borrowed connections there will be $f_i(minx_i) = mink_i$ free connections to the $(i + 1)$-th city. Increasing $minx_i$ by some $x$ we can get $f_i(minx_i + x) = mink_i + x$ free connections, but there is upper bound to number of free connections $maxk_i$. In other words, the function $f_i(minx_i + x) = \min(mink_i + x, maxk_i)$ where $x \ge 0$. For example, let's calculate the corresponding coefficients for the $i$-th function: if $a_i \le b_i$ then $minx_i = 0$, $mink_i = b_i - a_i$ and $maxk_i = b_i$; if $a_i > b_i$ then $minx_i = a_i - b_i$, $mink_i = 0$ and $maxk_i = b_i$. Why did we define such functions? If we can calculate result function $f_{[1,n]}(in) = f_n(f_{n - 1}(\dots f_2(f_1(in))\dots))$ then we can check the possibility of meeting all needs by checking that this fuction exists and $minx_{[1,n]} \le mink_{[1,n]}$, i. e. the minimum free $mink_{[1,n]}$ can be used as borrowed $minx_{[1,n]}$. Fortunately, it turns out that the superposition $f_{i+1}(f_i(in))$ is either don't exists (if, for example, $maxk_i < minx_{i + 1}$) or it has the same structure as any function $f_i$. So we can calculate $f_{[1,n]}$ in one pass and find the answer. We will skip the detailed formulas to calculate $f_{i+1}(f_i(in))$: you can either find them by yourself or look at function $merge()$ in author's solution. The resulting complexity is $O(n)$.
[ "binary search", "constructive algorithms", "data structures", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; typedef long long li; const int N = 1000 * 1000 + 13; int n; int a[N], b[N]; void solve() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &b[i]); li need = 0, add = 0, extra = 2e9; for (int i = n - 1; i >= 0; --i) { if (b[i] < need) { puts("NO"); return; } li val = b[i] - a[i]; li to_add = min(extra, max(0LL, val - need)); add += to_add; extra = min(extra - to_add, b[i] - need - to_add); need = max(0LL, need - val); } puts(add >= need ? "YES" : "NO"); } int main() { int t; scanf("%d", &t); for (int i = 0; i < t; ++i) solve(); }
1373
G
Pawns
You are given a chessboard consisting of $n$ rows and $n$ columns. Rows are numbered from bottom to top from $1$ to $n$. Columns are numbered from left to right from $1$ to $n$. The cell at the intersection of the $x$-th column and the $y$-th row is denoted as $(x, y)$. Furthermore, the $k$-th column is a special column. Initially, the board is empty. There are $m$ changes to the board. During the $i$-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules: - Pawn in the cell $(x, y)$ can be moved to the cell $(x, y + 1)$, $(x - 1, y + 1)$ or $(x + 1, y + 1)$; - You can make as many such moves as you like; - Pawns can not be moved outside the chessboard; - Each cell can not contain more than one pawn. The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers $n+1, n+2, n+3, \dots$. After each of $m$ changes, print one integer — the minimum number of rows which you have to add to make the board good.
For each pawn with initial position $(x, y)$ there exists a minimum index of row $i$ such that the pawn can reach the cell $(k, i)$, but cannot reach the cell $(k, i - 1)$. It's easy to see that $i = |k - x| + y$. In the resulting configuration, this pawn can occupy the cell $(k, i)$, $(k, i + 1)$, $(k, i + 2)$ or any other cell $(k, j)$ having $j \ge i$. Suppose the board consists of $r$ rows. For each row, the number of rows above it should be not less than the number of pawns that occupy the cells above it (that is, having $i$ greater than the index of that row) - because, if this condition is not fulfilled, we can't assign each pawn a unique cell. If we denote the number of pawns that should go strictly above the $j$-th row as $f(j)$, then for every row, the condition $f(j) \le r - j$ must be met. To prove that this condition is sufficient, we may, for example, use Hall's theorem. Okay, now what about finding the minimum $r$ satisfying it? Let's initially set $r$ to $n$, and for each row maintain the value of $j + f(j) - n$ - the minimum number of rows we have to add to our board so that the condition for the row $j$ is met (we also have to maintain this value for $n - 1$ auxiliary rows from $n + 1$ to $2n - 1$, since some pawns cannot fit in the initial board at all). Finding the minimum value we have to add to $r$ equals finding the maximum of all these values on some prefix (we don't need to look at the values on some rows with large indices, if there are no pawns after them, so we need a maximum query on the segment $[1, \max_i]$, where $\max_i$ is the maximum index $i$ among all pawns); and when a pawn is added or removed, we should add $+1$ or $-1$ to all values on some suffix. A segment tree with lazy propagation will do the trick, solving the problem for us in $O(m \log n)$.
[ "data structures", "divide and conquer", "greedy" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n, k; int m; int t[8 * N]; int add[8 * N]; int cnt[2 * N]; void push(int v, int l, int r) { if (r - l != 1 && add[v] != 0) { t[v * 2 + 1] += add[v]; t[v * 2 + 2] += add[v]; add[v * 2 + 1] += add[v]; add[v * 2 + 2] += add[v]; add[v] = 0; } } void upd(int v, int l, int r, int L, int R, int x) { if (L >= R) return; if(l == L && r == R) { t[v] += x; add[v] += x; return; } push(v, l, r); int mid = (l + r) / 2; upd(v * 2 + 1, l, mid, L, min(R, mid), x); upd(v * 2 + 2, mid, r, max(L, mid), R, x); t[v] = max(t[v * 2 + 1], t[v * 2 + 2]); } void upd(int l, int r, int x) { upd(0, 0, n + n, l, r, x); } int get(int v, int l, int r, int L, int R) { if (L >= R) return 0; if (l == L && r == R) return t[v]; push(v, l, r); int mid = (l + r) >> 1; return max(get(v * 2 + 1, l, mid, L, min(R, mid)) , get(v * 2 + 2, mid, r, max(L, mid), R)); } int get(int l, int r) { return get(0, 0, n + n, l, r); } int getAns(set <int> &smx) { if (smx.empty()) return 0; return max(0, get(0, *smx.rbegin() + 1) - n); } void build(int v, int l, int r) { if (r - l == 1) { t[v] = l; return; } int mid = (l + r) >> 1; build(v * 2 + 1, l, mid); build(v * 2 + 2, mid, r); t[v] = max(t[v * 2 + 1], t[v * 2 + 2]); } int main(){ scanf("%d %d %d", &n, &k, &m); build(0, 0, n + n); set <pair<int, int> > s; set <int> smx; for (int i = 0; i < m; ++i) { int x, y; scanf("%d %d", &x, &y); int pos = abs(x - k) + y - 1; pair <int, int> p = make_pair(x, y); if (s.count(p)) { --cnt[pos]; if (cnt[pos] == 0) smx.erase(pos); upd(0, pos + 1, -1); s.erase(p); } else { ++cnt[pos]; if (cnt[pos] == 1) smx.insert(pos); upd(0, pos + 1, 1); s.insert(p); } printf("%d\n", getAns(smx)); } return 0; }
1374
A
Required Remainder
You are given three integers $x, y$ and $n$. Your task is to find the \textbf{maximum} integer $k$ such that $0 \le k \le n$ that $k \bmod x = y$, where $\bmod$ is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given $x, y$ and $n$ you need to find the maximum possible integer from $0$ to $n$ that has the remainder $y$ modulo $x$. You have to answer $t$ independent test cases. It is guaranteed that such $k$ exists for each test case.
There are two cases in this problem. If we try to maximize the answer, we need to consider only two integers: $n - n \bmod x + y$ and $n - n \bmod x - (x - y)$. Of course, the first one is better (we get rid of the existing remainder and trying to add $y$ to this number). If it's too big, then we can and need to take the second one (this number is just the first one but decreased by $x$). The answer can be always found between these numbers. Time complexity: $O(1)$.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int x, y, n; cin >> x >> y >> n; if (n - n % x + y <= n) { cout << n - n % x + y << endl; } else { cout << n - n % x - (x - y) << endl; } } return 0; }
1374
B
Multiply by 2, divide by 6
You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder). Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that. You have to answer $t$ independent test cases.
If the number consists of other primes than $2$ and $3$ then the answer is -1. Otherwise, let $cnt_2$ be the number of twos in the factorization of $n$ and $cnt_3$ be the number of threes in the factorization of $n$. If $cnt_2 > cnt_3$ then the answer is -1 because we can't get rid of all twos. Otherwise, the answer is $(cnt_3 - cnt_2) + cnt_3$. Time complexity: $O(\log{n})$.
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; int cnt2 = 0, cnt3 = 0; while (n % 2 == 0) { n /= 2; ++cnt2; } while (n % 3 == 0) { n /= 3; ++cnt3; } if (n == 1 && cnt2 <= cnt3) { cout << 2 * cnt3 - cnt2 << endl; } else { cout << -1 << endl; } } return 0; }
1374
C
Move Brackets
You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'. In one move, you can choose \textbf{exactly one bracket} and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$). Your task is to find the minimum number of moves required to obtain \textbf{regular bracket sequence} from $s$. It can be proved that the answer always exists under the given constraints. Recall what the regular bracket sequence is: - "()" is regular bracket sequence; - if $s$ is regular bracket sequence then "(" + $s$ + ")" is regular bracket sequence; - if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not. You have to answer $t$ independent test cases.
Let's go from left to right over characters of $s$ maintaining the current bracket balance (for the position $i$ the balance is the number of opening brackets on the prefix till the $i$-th character minus the number of closing brackets on the same prefix). If the current balance becomes less than zero, then let's just take some opening bracket after the current position (it obviously exists because the number of opening equals the number of closing brackets) and move it to the beginning (so the negative balance becomes zero again and the answer increases by one). Or we can move the current closing bracket to the end of the string because it leads to the same result. Time complexity: $O(n)$.
[ "greedy", "strings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; int ans = 0; int bal = 0; for (int i = 0; i < n; ++i) { if (s[i] == '(') ++bal; else { --bal; if (bal < 0) { bal = 0; ++ans; } } } cout << ans << endl; } return 0; }
1374
D
Zero Remainder Array
You are given an array $a$ consisting of $n$ positive integers. Initially, you have an integer $x = 0$. During one move, you can do one of the following two operations: - Choose \textbf{exactly one} $i$ from $1$ to $n$ and increase $a_i$ by $x$ ($a_i := a_i + x$), then increase $x$ by $1$ ($x := x + 1$). - Just increase $x$ by $1$ ($x := x + 1$). The first operation can be applied \textbf{no more than once} to each $i$ from $1$ to $n$. Your task is to find the minimum number of moves required to obtain such an array that each its element is \textbf{divisible by} $k$ (the value $k$ is given). You have to answer $t$ independent test cases.
Firstly, we can understand that during each full cycle of $x$ from $0$ to $k-1$ we can fix each remainder only once. Notice that when we add some $x$ then we fix the remainder $k-x$ (and we don't need to fix elements which are already divisible by $k$). So, let $cnt_i$ be the number of such elements for which the condition $k - a_i \bmod k = i$ holds (i.e. the number of such elements that we can fix if we add the value $i \bmod k$ to them). We can count this using some logarithmic data structure (like std::map in C++). So, what's the number of full cycles? It equals to the amount of most frequent element in $cnt$ minus one. So, the answer is at least $k \cdot (max(cnt) - 1)$. And there can be one last cycle which will be incomplete. So what is the remanining number of moves? It equals to the maximum possible $i$ among all $cnt_i = max(cnt)$. So if $key$ is the maximum such $i$ that $cnt_{key} = max(cnt)$ then the answer is $k \cdot (cnt_{key} - 1) + key + 1$. Time complexity: $O(n \log{n})$.
[ "math", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &it : a) cin >> it; map<int, int> cnt; int mx = 0; for (auto &it : a) { if (it % k == 0) continue; ++cnt[k - it % k]; mx = max(mx, cnt[k - it % k]); } long long ans = 0; for (auto [key, value] : cnt) { if (value == mx) { ans = k * 1ll * (value - 1) + key + 1; } } cout << ans << endl; } return 0; }
1374
E1
Reading Books (easy version)
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book \textbf{together} to end this exercise faster. There are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not). So they need to choose some books from the given $n$ books in such a way that: - Alice likes \textbf{at least} $k$ books from the chosen set and Bob likes \textbf{at least} $k$ books from the chosen set; - the total reading time of these books is \textbf{minimized} (they are children and want to play and joy as soon a possible). The set they choose is \textbf{the same} for both Alice an Bob (it's shared between them) and they read all books \textbf{together}, so the total reading time is the sum of $t_i$ over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.
Let's divide all books into four groups: 00 - both Alice and Bob doesn't like these books; 01 - only Alice likes these books; 10 - only Bob likes these books; 11 - both ALice and Bob like these books. Obviously, 00-group is useless now. So, how to solve the problem? Let's iterate over the number of books we take from 11-group. Let it be $cnt$. Then we obviously need to take exactly $k-cnt$ books from groups 01 and 10. Among all books in these three groups we have to choose the cheapest ones. To calculate sum of times in each group fast enought, we can sort each group independently and implement prefix sums on these arrays. If $k-cnt$ is less than zero or greater than the size of 01 or 10-group for each possible $cnt$ then the answer is -1. And don't forget that the answer can be up to $2 \cdot 10^9$. Time complexity: $O(n \log{n})$.
[ "data structures", "greedy", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; const int INF = 2e9 + 1; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> times[4]; vector<int> sums[4]; for (int i = 0; i < n; ++i) { int t, a, b; cin >> t >> a >> b; times[a * 2 + b].push_back(t); } for (int i = 0; i < 4; ++i) { sort(times[i].begin(), times[i].end()); sums[i].push_back(0); for (auto it : times[i]) { sums[i].push_back(sums[i].back() + it); } } int ans = INF; for (int cnt = 0; cnt < min(k + 1, int(sums[3].size())); ++cnt) { if (k - cnt < int(sums[1].size()) && k - cnt < int(sums[2].size())) { ans = min(ans, sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt]); } } if (ans == INF) ans = -1; cout << ans << endl; return 0; }
1374
E2
Reading Books (hard version)
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read \textbf{exactly} $m$ books before all entertainments. Alice and Bob will read each book \textbf{together} to end this exercise faster. There are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not). So they need to choose \textbf{exactly} $m$ books from the given $n$ books in such a way that: - Alice likes \textbf{at least} $k$ books from the chosen set and Bob likes \textbf{at least} $k$ books from the chosen set; - the total reading time of these $m$ books is \textbf{minimized} (they are children and want to play and joy as soon a possible). The set they choose is \textbf{the same} for both Alice an Bob (it's shared between them) and they read all books \textbf{together}, so the total reading time is the sum of $t_i$ over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.
A little explanation: this editorial will be based on the easy version editorial so I'll use some definitions from it. Here we go, the most beautiful problem of the contest is waiting us. Well, the key idea of this problem almost the same with the easy version idea. Let's iterate over the number of elements in 11-group, we need to take the cheapest ones again. If the number of elements we take from 11-group is $cnt$ then we need to take $k-cnt$ elements from 01 and 10-groups. But one more thing: let's iterate over $cnt$ not from zero but from the smallest possible number which can give us any correct set of books (the numeric value of the answer doesn't matter) $start$. The value of $start$ can be calculated using $k, m$ and sizes of groups by formula or even simple loop. If we can't find any suitable value of $start$, the answer is -1. Let's call $cnt$ elements from 11-group and $k-cnt$ elements from 01 and 10-groups we take necessary. Other elements of the whole set of books are free (but elements of 11-group are not free). Let's create the set $fr$ which contains all free elements (and fill it beforehand). So, now we took some necessary elements, but we need to take some free elements to complete our set. Let's create the other set $st$ which contains free elements we take to the answer (and maintain the variable $sum$ describing the sum of elements of $st$). How do we recalculate $st$? Before the start of the first iteration our set $fr$ is already filled with some elements, let's update $st$ using them. Update is such an operation (function) that tosses the elements between $fr$ and $st$. It will do the following things (repeatedly, and stop when it cannot do anything): While the size of $st$ is greater than needed (so we take more than $m$ books in total), let's remove the most expensive element from $st$ and add it to $fr$; while the size of $st$ is less than needed (so we take less than $m$ books in total), let's remove the cheapest element from $fr$ and add it to $st$; while the cheapest element from $fr$ is cheaper than the most expensive element form $st$, let's swap them. Note that during updates you need to recalculate $sum$ as well. So, we go over all possible values $cnt$, updating $st$ before the first iteration and after each iteration. The size of both sets changes pretty smooth: if we go from $cnt$ to $cnt+1$, we need to remove at most one element from $st$ (because we take one element from 11-group during each iteration) and we need to add at most two elements to $st$ and $fr$ (because we remove at most two elements from 01 and 10-groups during one iteration). To restore the answer, let's save such a value $cnt$ that the answer is minimum with this value $cnt$ (let it be $pos$). Then let's just run the same simulation once more from the beginning but stop when we reach $pos$. Then $st$ will contain free elements we need to take to the answer, $pos$ describes the number of elements we need to take from 11-group and $k-pos$ describes which elements from 01 and 01-groups we need to take. Of course, there are some really tough technical things like case-handling (there is a lot of cases, for example, the size of $st$ can be negative at some moment and you need to carefully handle that, and $k-cnt$ can be negative after some number of iterations and there are other cases because of that, and so on). Time complexity: $O(n \log{n})$.
[ "data structures", "greedy", "implementation", "sortings", "ternary search", "two pointers" ]
2,500
#include <bits/stdc++.h> using namespace std; const int INF = 2e9 + 1; #define size(a) int((a).size()) void updateSt(set<pair<int, int>> &st, set<pair<int, int>> &fr, int &sum, int need) { need = max(need, 0); while (true) { bool useful = false; while (size(st) > need) { sum -= st.rbegin()->first; fr.insert(*st.rbegin()); st.erase(prev(st.end())); useful = true; } while (size(st) < need && size(fr) > 0) { sum += fr.begin()->first; st.insert(*fr.begin()); fr.erase(fr.begin()); useful = true; } while (!st.empty() && !fr.empty() && fr.begin()->first < st.rbegin()->first) { sum -= st.rbegin()->first; sum += fr.begin()->first; fr.insert(*st.rbegin()); st.erase(prev(st.end())); st.insert(*fr.begin()); fr.erase(fr.begin()); useful = true; } if (!useful) break; } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; cin >> n >> m >> k; vector<pair<int, int>> times[4]; vector<int> sums[4]; for (int i = 0; i < n; ++i) { int t, a, b; cin >> t >> a >> b; times[a * 2 + b].push_back({t, i}); } for (int i = 0; i < 4; ++i) { sort(times[i].begin(), times[i].end()); sums[i].push_back(0); for (auto it : times[i]) { sums[i].push_back(sums[i].back() + it.first); } } int ans = INF; int pos = INF; set<pair<int, int>> st; set<pair<int, int>> fr; int sum = 0; vector<int> res; for (int iter = 0; iter < 2; ++iter) { st.clear(); fr.clear(); sum = 0; int start = 0; while (k - start >= size(sums[1]) || k - start >= size(sums[2]) || m - start - (k - start) * 2 < 0) { ++start; } if (start >= size(sums[3])) { cout << -1 << endl; return 0; } int need = m - start - (k - start) * 2; for (int i = 0; i < 3; ++i) { for (int p = size(times[i]) - 1; p >= (i == 0 ? 0 : k - start); --p) { fr.insert(times[i][p]); } } updateSt(st, fr, sum, need); for (int cnt = start; cnt < (iter == 0 ? size(sums[3]) : pos); ++cnt) { if (k - cnt >= 0) { if (cnt + (k - cnt) * 2 + size(st) == m) { if (ans > sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum) { ans = sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum; pos = cnt + 1; } } } else { if (cnt + size(st) == m) { if (ans > sums[3][cnt] + sum) { ans = sums[3][cnt] + sum; pos = cnt + 1; } } } if (iter == 1 && cnt + 1 == pos) break; need -= 1; if (k - cnt > 0) { need += 2; fr.insert(times[1][k - cnt - 1]); fr.insert(times[2][k - cnt - 1]); } updateSt(st, fr, sum, need); } if (iter == 1) { for (int i = 0; i + 1 < pos; ++i) res.push_back(times[3][i].second); for (int i = 0; i <= k - pos; ++i) { res.push_back(times[1][i].second); res.push_back(times[2][i].second); } for (auto [value, position] : st) res.push_back(position); } } cout << ans << endl; for (auto it : res) cout << it + 1 << " "; cout << endl; return 0; }
1374
F
Cyclic Shifts Sorting
You are given an array $a$ consisting of $n$ integers. In one move, you can choose some index $i$ ($1 \le i \le n - 2$) and shift the segment $[a_i, a_{i + 1}, a_{i + 2}]$ cyclically to the right (i.e. replace the segment $[a_i, a_{i + 1}, a_{i + 2}]$ with $[a_{i + 2}, a_i, a_{i + 1}]$). Your task is to sort the initial array by \textbf{no more than $n^2$ such operations} or say that it is impossible to do that. You have to answer $t$ independent test cases.
Firstly, let's solve the easier version of the problem. Assume we are given a permutation, not an array. Notice that the given operation applied to some segment of the permutation cannot change the parity of number of inversions (the number of inversions is the number of such pairs of indices $(i, j)$ that $j > i$ and $a_j < a_i$). So if the number of inversions in the given permutation is odd then we can't sort this permutation (we can't obtain zero inversions). But if the number of inversions is even then we can always sort the permutation with the following greedy algorithm: let's find the minimum element and move it to the first position. If its position is $i$ then we can apply the operation to the segment $[i-2; i]$ and our element will move by two positions to the left. So, after all, our element is either at the first or at the second position. If it's at the second position, let's just apply two additional operations to the segment $[1; 3]$. Then let's just cut off the first element and solve the problem without it. At the end we have only two numbers that can be not sorted and we can check all three possibilities and choose one which is suitable for us (it's always exists because the number of inversions is even). How do we solve the problem if we are given the array, not the permutation? First of all, we can prove that if the array contains at least two equal elements, we can always sort it (we will prove it by construction). Let's just renumerate the elements of the given array in a way to obtian the permutation with the even number of inversions. Thus, if $a[i_1] \le a[i_2] \le \dots \le a[i_n]$ then let's find such a permutation $p$ that $p[i_1] < p[i_2] < \dots < p[i_n]$. We can find this permutation easily if we sort the array of pairs $(a_i, i)$ in increasing order. But there can be one problem: this permutation can have odd number of inversions. Then we need to find two consecutive pairs with the same first values and swap these two elements in the permutation. Because in fact these two numbers are equal in the array and have consecutive values in the permutation, we guaranteed change the parity of number of inversions. Then we can apply our algorithm for permutations and solve the problem for the array. If we failed then the answer is -1. Otherwise the number of operations always does not exceed $n^2$ (because this sort works like a bubble sort) so our answer is suitable. Time complexity: $O(n^2)$.
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif auto make = [](vector<int> &a, int pos) { swap(a[pos + 1], a[pos + 2]); swap(a[pos], a[pos + 1]); }; int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); vector<pair<int, int>> res(n); for (int i = 0; i < n; ++i) { cin >> a[i]; res[i] = { a[i], i }; } sort(res.begin(), res.end()); for (int i = 0; i < n; ++i) { a[res[i].second] = i; } int cnt = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { cnt += a[j] < a[i]; } } if (cnt & 1) { for (int i = 0; i < n - 1; ++i) { if (res[i].first == res[i + 1].first) { swap(a[res[i].second], a[res[i + 1].second]); break; } } } vector<int> ans; for (int i = 0; i < n - 2; ++i) { int pos = min_element(a.begin() + i, a.end()) - a.begin(); while (pos > i + 1) { make(a, pos - 2); ans.push_back(pos - 2); pos -= 2; } if (pos != i) { make(a, i); make(a, i); ans.push_back(i); ans.push_back(i); pos = i; } } for (int i = 0; i < 3; ++i) { if (is_sorted(a.begin(), a.end())) { break; } make(a, n - 3); ans.push_back(n - 3); } if (!is_sorted(a.begin(), a.end())) { cout << -1 << endl; } else { cout << ans.size() << endl; for (auto it : ans) cout << it + 1 << " "; cout << endl; } } return 0; }
1375
A
Sign Flipping
You are given $n$ integers $a_1, a_2, \dots, a_n$, where $n$ \textbf{is odd}. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: - At least $\frac{n - 1}{2}$ of the adjacent differences $a_{i + 1} - a_i$ for $i = 1, 2, \dots, n - 1$ are \textbf{greater than or equal to} $0$. - At least $\frac{n - 1}{2}$ of the adjacent differences $a_{i + 1} - a_i$ for $i = 1, 2, \dots, n - 1$ are \textbf{less than or equal to} $0$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.
Notice that $a_{i + 1} - a_i \ge 0$ is equivalent to $a_{i + 1} \ge a_i$. Similarly $a_{i + 1} - a_i \le 0$ is equivalent to $a_{i + 1} \le a_i$. Flip the signs in such a way that $a_i \ge 0$ for odd $i$, while $a_i \le 0$ for even $i$. Then $a_{i + 1} \ge 0 \ge a_i$, and thus $a_{i + 1} \ge a_i$, for $i = 2, 4, \dots, n - 1$. $a_{i + 1} \le 0 \le a_i$, and thus $a_{i + 1} \le a_i$, for $i = 1, 3, \dots, n - 2$. Giving at least $\frac{n - 1}{2}$ of each, as desired.
[ "constructive algorithms", "math" ]
1,100
null
1375
B
Neighbor Grid
You are given a grid with $n$ rows and $m$ columns, where each cell has a non-negative integer written on it. We say the grid is \textbf{good} if for each cell the following condition holds: if it has a number $k > 0$ written on it, then exactly $k$ of its neighboring cells have a number greater than $0$ written on them. Note that if the number in the cell is $0$, there is no such restriction on neighboring cells. You are allowed to take any number in the grid and increase it by $1$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them. Two cells are considered to be neighboring if they have a common edge.
For every cell $(i, j)$ let's denote by $n_{i, j}$ the number of neighbors it has (either zero or non-zero, it doesn't matter). Then for each cell, it must hold that $a_{i, j} \le n_{i, j}$, otherwise, no solution exists because it is impossible to decrease $a_{i, j}$. Let's now suppose that $a_{i, j} \le n_{i, j}$ for all cells $(i, j)$. Then a solution always exists: We can increase each $a_{i, j}$ to make it equal to $n_{i, j}$. This always works because every number will be non-zero, so every neighbor of every cell will be non-zero, and every cell has a value equal to its number of neighbors.
[ "constructive algorithms", "greedy" ]
1,200
null
1375
C
Element Extermination
You are given an array $a$ of length $n$, which initially is a \textbf{permutation} of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $[1, 3, 2]$, you can choose $i = 1$ (since $a_1 = 1 < a_2 = 3$), then either remove $a_1$ which gives the new array $[3, 2]$, or remove $a_2$ which gives the new array $[1, 2]$. Is it possible to make the length of this array equal to $1$ with these operations?
The answer is YES iff $a_1 < a_n$. Let's find out why. When $a_1 < a_n$, we can repeatedly use this algorithm while the permutation contains more than one element: Find the smallest index $r$ such that $a_1 < a_r$. Choose $a_r$ and the element comes right before $a_r$ and delete the element before $a_r$. Repeat step 2 until $a_r$ is adjacent to $a_1$. Choose $a_1$ and $a_r$, and delete $a_r$. When $a_1 > a_n$, we have some observations: The leftmost element is non-decreasing. That is because if we want to remove the old leftmost element $a_1$, we need to pair it with $a_2 > a_1$, and that will result in the leftmost element increasing. Likewise, we can use the same argument to show that the rightmost element is non-increasing.
[ "constructive algorithms", "data structures", "greedy" ]
1,400
null
1375
D
Replace by MEX
You're given an array of $n$ integers between $0$ and $n$ inclusive. In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation). For example, if the current array is $[0, 2, 2, 1, 4]$, you can choose the second element and replace it by the MEX of the present elements  — $3$. Array will become $[0, 3, 2, 1, 4]$. You must make the array non-decreasing, using at most $2n$ operations. It can be proven that it is always possible. Please note that you do \textbf{not} have to minimize the number of operations. If there are many solutions, you can print any of them. – An array $b[1 \ldots n]$ is non-decreasing if and only if $b_1 \le b_2 \le \ldots \le b_n$. The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: - The MEX of $[2, 2, 1]$ is $0$, because $0$ does not belong to the array. - The MEX of $[3, 1, 0, 1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not. - The MEX of $[0, 3, 1, 2]$ is $4$ because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not. It's worth mentioning that the MEX of an array of length $n$ is always between $0$ and $n$ inclusive.
(We consider the array $0$-indexed) Instead of trying to reach any non-decreasing array, we will try to reach precisely $[0, 1, \ldots, n-1]$. Let's call any index $i$ such that $a_i \neq i$ an unfixed point. We will repeat the following procedure in order to remove all unfixed points: If $\text{mex} = n$, we apply an operation on any unfixed point. Now that $\text{mex} < n$, we apply an operation on index $\text{mex}$ (which was an unfixed point, since $\text{mex}$ was not present in the array). Each turn uses at most $2$ operations, and decrease the number of unfixed points by exactly $1$. Since there are at most $n$ unfixed points initially, we use at most $2n$ operations. It was not necessary under the given constraints, but one can notice that if $\text{mex} = n$, the current array is a permutation, and that solving a cycle will take $\text{size} + 1$ operations. Hence, the described algorithm use in fact at most $1.5n$ operations, the worst case being $[1, 0, 3, 2, 5, 4, \ldots]$ when there are a lot of $2$-cycles. Since the constraint on $n$ is low, we can recompute naively the $\text{mex}$ each time in $\mathcal{O}(n)$, leading to an $\mathcal{O}(n^2)$ final time complexity.
[ "brute force", "constructive algorithms", "sortings" ]
1,900
null
1375
E
Inversion SwapSort
Madeline has an array $a$ of $n$ integers. A pair $(u, v)$ of integers forms an inversion in $a$ if: - $1 \le u < v \le n$. - $a_u > a_v$. Madeline recently found a magical paper, which allows her to write two indices $u$ and $v$ and swap the values $a_u$ and $a_v$. Being bored, she decided to write a list of pairs $(u_i, v_i)$ with the following conditions: - all the pairs in the list are distinct and form an inversion in $a$. - all the pairs that form an inversion in $a$ are in the list. - Starting from the given array, if you swap the values at indices $u_1$ and $v_1$, then the values at indices $u_2$ and $v_2$ and so on, then after all pairs are processed, the array $a$ will be sorted in \textbf{non-decreasing order}. Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.
We can prove that the answer always exists. Let's first solve the problem for a permutation of length $n$. Let's define $pos_i (1 \le i \le n)$ as the index of $i$ in the permutation. First we are going to use all the pairs whose second element is $n$. Let's define the resulting permutation that we get, after using all these pairs in some order, as $b$. We want $b$ to satisfy all of these conditions. $b_n=n$ If $a_i>a_j$ then $b_i>b_j$ ($1 \le i<j \le n-1$) If $a_i<a_j$ then $b_i<b_j$ ($1 \le i<j \le n-1$) So we solved the problem for a permutation, how can we approach the general problem? For every $i>j, a_i=a_j$ we can assume that $a_i>a_j$, and this won't change anything because the order of equal elements doesn't matter and we are not adding any inversions by assuming this. So after doing this we can easily squeeze the numbers into a permutation and solve the problem for a permutation. Total complexity $O(n^2logn)$ or $O(n^2)$.
[ "constructive algorithms", "greedy", "sortings" ]
2,500
null
1375
F
Integer Game
\textbf{This is an interactive problem.} Anton and Harris are playing a game to decide which of them is the king of problemsetting. There are three piles of stones, initially containing $a$, $b$, and $c$ stones, where $a$, $b$, and $c$ are \textbf{distinct} positive integers. On each turn of the game, the following sequence of events takes place: - The first player chooses a positive integer $y$ and provides it to the second player. - The second player adds $y$ stones to one of the piles, with the condition that \textbf{he cannot choose the same pile in two consecutive turns}. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $1000$ turns have passed without the second player losing. Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
Let's prove that the first player can always win in at most three turns. Assume that the initial numbers of stones are $p < q < r$. On the first turn, choose $y = 2r - p - q$. We then have three cases: Case 1. $y$ is added to $p$. The piles now have $2r - q$, $q$ and $r$ stones. Now choose $y = r - q$. Since the pile with $2r - q$ stones cannot be chosen on this turn, this results in a win. Case 2. $y$ is added to $q$. The piles now have $p$, $2r - p$ and $r$ stones. Choose $y = r - p$. Similarly to the previous case this results in a win since the pile with $2r - p$ stones cannot be chosen on this turn. Case 3. $y$ is added to $r$. The piles have $p < q < 3r - p - q$ stones. We now have a situation similar to the initial one, with the difference that the pile with the largest number of stones cannot be chosen on the next turn. Thus we may repeat the strategy and obtain a guaranteed win this time.
[ "constructive algorithms", "games", "interactive", "math" ]
2,600
null
1375
G
Tree Modification
You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: - Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$. - For every vertex $d$ \textbf{other than $b$} that is adjacent to $a$, remove the edge connecting $d$ and $a$ and add the edge connecting $d$ and $c$. - Delete the edge connecting $a$ and $b$ and add the edge connecting $a$ and $c$. As an example, consider the following tree: The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $2$, $4$, and $5$: It can be proven that after each operation, the resulting graph is still a tree. Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $n - 1$, called its center, and $n - 1$ vertices of degree $1$.
The solution is based on the following observation: Every tree is a bipartite graph, i. e. its vertices can be colored black or white in such a way that every white vertex is adjacent only to black vertices and vice versa. Notice that a tree is a star if and only if one of the colors appears exactly once. Let's fix a bipartite coloring of the tree and look at what happens when we apply the operation to vertices $a$, $b$, and $c$. For concreteness, let's suppose that $b$ is black, so $a$ and $c$ must be white. When we perform the operation: Every neighbor of $a$ other than $b$ is black. After connecting it to $c$ it remains black since $c$ is white. After connecting $a$ to $c$ it must switch from being white to being black since $c$ is white. Every other vertex is unaffected by the operation. Thus every operation changes the color of exactly one vertex! Suppose that initially there are $b$ black vertices and $w$ white vertices. Then we need at least $\min(w, b) - 1$ operations to turn the tree into a star since one of the colors must end up having a single vertex. This is always achievable: as long as there are at least two vertices with a certain color we can choose two which are adjacent to a common neighbor and use the operation to recolor one of them. The values of $w$ and $b$ can be found through a simple DFS, leading to an $O(n)$ solution.
[ "brute force", "constructive algorithms", "dfs and similar", "graph matchings", "graphs", "trees" ]
2,800
null
1375
H
Set Merging
You are given a permutation $a_1, a_2, \dots, a_n$ of numbers from $1$ to $n$. Also, you have $n$ sets $S_1,S_2,\dots, S_n$, where $S_i=\{a_i\}$. Lastly, you have a variable $cnt$, representing the current number of sets. Initially, $cnt = n$. We define two kinds of functions on sets: $f(S)=\min\limits_{u\in S} u$; $g(S)=\max\limits_{u\in S} u$. You can obtain a new set by merging two sets $A$ and $B$, if they satisfy $g(A)<f(B)$ (Notice that the old sets do not disappear). Formally, you can perform the following sequence of operations: - $cnt\gets cnt+1$; - $S_{cnt}=S_u\cup S_v$, you are free to choose $u$ and $v$ for which $1\le u, v < cnt$ and which satisfy $g(S_u)<f(S_v)$. You are required to obtain some specific sets. There are $q$ requirements, each of which contains two integers $l_i$,$r_i$, which means that there must exist a set $S_{k_i}$ ($k_i$ is the ID of the set, you should determine it) which equals $\{a_u\mid l_i\leq u\leq r_i\}$, which is, the set consisting of all $a_i$ with indices between $l_i$ and $r_i$. In the end you must ensure that $cnt\leq 2.2\times 10^6$. Note that you \textbf{don't} have to minimize $cnt$. It is guaranteed that a solution under given constraints exists.
First, two sets $a$ and $b$ can be merged if and only if the range of elements in $a$ do not intersect with the range of elements in $b$. It is obvious because if they intersect, neither $g(a)<f(b)$ nor $g(b)<f(a)$ are satisfied. If they do not intersect, there must be one of them satisfied. Notice that $2\times n\sqrt{q}$ is near to $2.2\times 10^6$, this hints us to use sqrt-decomposition. We separate the numbers $1,2,\cdots,n$ into $\dfrac{n}{S}$ consecutive blocks, each of size $S$. Consider a block $B_i=[l,r]$, we take all elements in the original permutation that satisfy $l\leq a_i \leq r$, and form a new sequence that preserves the original order. For example, if the permutation $9,8,2,1,5,6,3,7,4$ is divided into $3$ blocks $B_1=[1,3],B_2=[4,6],B_3=[7,9]$, their sequences will be $2,1,3$ and $5,6,4$ and $9,8,7$. Consider any consecutive subsequence in the permutation. We want to construct a set that just contains all elements in it. We can first divide this subsequence into $\dfrac{n}S$ subsequences in each block that contains only elements in this block and merge them up. For example, if we want the subsequence $8,2,1,5,6,3,7$ in the permutation above, then we can divide it into $2,1,3$ and $5,6$ and $8,7$. Notice that those subsequences in each block are also consecutive subsequences. Also, notice that since the range of elements in each block do not intersect, the range of elements in these subsequences also do not intersect. This means that if we can somehow construct the set that equals the set of each of those subsequences, we can just merge those subsequences of each block to form the original subsequence that we want to obtain in $\dfrac{n}S-1$ merges. Thus the process of constructing sets in total costs less that $\dfrac{qn}S$ merges. Now we have to construct the subsequences of each block, notice that the subsequences are consecutive, thus we can just construct sets of all of those $\dfrac12S(S+1)$ consecutive subsequences. Consider divide and conquer. We can divide a sequence in to two parts of equal size, construct subsequences of them, and try to merge them to obtain the new sets. So how do we split and merge? Consider two sequences, that elements in the first sequence is less than elements in the second, and we have already constructed the sets of all the consecutive subsequences in each of those sequences. Now we consider a sequence that contains the union of the elements in the two subsequences. All elements in sequences here are ordered according to the order in the original permutation. Now we want to construct all the consecutive subsequences in the new sequence. Consider for each consecutive subsequence in the new sequence, it must be composed by two parts, the ones present in the first sequence, and the one present in the second. It is obvious that each part is also a consecutive subsequence in the respective sequence, thus the sets representing them is already constructed. Because the two sequence do not intersect in range of elements, we can just merge those two sets to form the new one. For example, we want to obtain all subsequences of the sequence $1,4,3,2,6,5$, and we have already obtained the ones of $1,3,2$ and $4,6,5$. So if we want to get the consecutive subsequence $1,4,3,2,6$, we first divide it into $1,3,2$ and $4,6$. Because the sets of them are already constructed(they are consecutive subsequences of $1,3,2$ and $4,6,5$), and their range of elements do not intersect, we can merge it in one operation. Other consecutive subsequences can also be obtained similarly. Thus there are $\dfrac12S(S+1)$ subsequences, and less than $\dfrac12S(S-1)$ need a merge operation (because those with only one element in it need no operation). We use $f(S)$ to denote the number of operation needed to construct all consecutive subsequences of a block of length $S$ There is $f(1)=0$ and $f(x)\leq \dfrac12x^2+f(\lfloor x/2\rfloor)+f(\lceil x/2\rceil)$,(if we divide a subsequence evenly),it can be proved that $f(x)\leq x^2$ So, we need $\dfrac{n}S\times S^2$ operations to construct all consecutive subsequences. So in total, $nS+\dfrac{nq}S$ operations are needed. According to the mean inequality, there is $nS+\dfrac{nq}S\geq 2\sqrt{n^2q}=2n\sqrt{q}$, and if $S=\sqrt{q}$, $nS+\dfrac{nq}S=2\sqrt{n^2q}=2n\sqrt{q}$ And, $2n\sqrt{q}\leq 2^{21}< 2.2\times 10^6$, thus the restriction is satisfied. Also, there exists a solution based on segment-tree. The main idea is to maintain a segment-tree of $1$ to $n$, in each node, we save a hash-map of sets with elements in the range of that node already constructed. Anytime we want a new set, we do a query on the segment tree, if the set on that node is constructed, we return it. Otherwise, we split the wanted set into two parts, and query on its sons, and merge them. The details is omitted due to laziness issue. And we find that this solution can pass, why? Suppose $n=2^N$ and $q=2^Q$ We can calculate that we need no more than $\sum_{i=0}^n 2^{N-i}\min(2^{2i-1},2^Q)$ sets. This is because in the $i$th layer(bottom to top) of the segment-tree, there are $2^{N-i}$ nodes, each one can contain no more than $2^i(2^i-1)/2$ sets (the consecutive subsegment limitation). but it is also bounded by $2^Q$ queries, because a query can only visit a node at most once. Calculating this sum yield a bound lower that the resiriction. Also we can find that this solution is similar to the previous sol. We find that For $i \leq Q/2$,the sum is $\sum_{i=0}^{Q/2} 2^{N-i}2^{2i-1}= \sum_{i=0}^{Q/2} 2^{N+i-1}\leq 2^{N+Q/2}$ And for $i> Q/2$ the sum is $2^Q \sum_{i=Q/2+1}^N 2^{N-i}\leq 2^Q 2^{N-Q/2}=2^{N+Q/2}$ Summing these two parts yield $2^{N+Q/2+1}$ which is also $2n\sqrt{q}$ So these solutions have the same complexity. Other than that, we observe that the lower-$Q/2$ layers is just like those blocks constructed in the first solution, only the merging in the upper one is different, the first solution used brute-force, while the second just extended the segment-tree up. Thus, we say that the first solution is just the second one, but bounded manually. So these two solutions are intrinsically similar.
[ "constructive algorithms", "divide and conquer" ]
3,300
null
1375
I
Cubic Lattice
A cubic lattice $L$ in $3$-dimensional euclidean space is a set of points defined in the following way: $$L=\{u \cdot \vec r_1 + v \cdot \vec r_2 + w \cdot \vec r_3\}_{u, v, w \in \mathbb Z}$$ Where $\vec r_1, \vec r_2, \vec r_3 \in \mathbb{Z}^3$ are some integer vectors such that: - $\vec r_1$, $\vec r_2$ and $\vec r_3$ are pairwise orthogonal: $$\vec r_1 \cdot \vec r_2 = \vec r_1 \cdot \vec r_3 = \vec r_2 \cdot \vec r_3 = 0$$ Where $\vec a \cdot \vec b$ is a dot product of vectors $\vec a$ and $\vec b$. - $\vec r_1$, $\vec r_2$ and $\vec r_3$ all have the same length: $$|\vec r_1| = |\vec r_2| = |\vec r_3| = r$$ You're given a set $A=\{\vec a_1, \vec a_2, \dots, \vec a_n\}$ of integer points, $i$-th point has coordinates $a_i=(x_i;y_i;z_i)$. Let $g_i=\gcd(x_i,y_i,z_i)$. It is guaranteed that $\gcd(g_1,g_2,\dots,g_n)=1$.You have to find a cubic lattice $L$ such that $A \subset L$ and $r$ is the maximum possible.
$2$-dimensional version of this problem appeared as problem K in Makoto Soejima Contest 4 from Petrozavodsk Winter Training Camp 2016 (Also known as GP of Asia in OpenCup XVI). Solution for this case is based on the fact that the whole lattice equation may be represented as the product of two Gaussian integers $a_k = \alpha_k \cdot g$, where $g$ is the complex number representing $(\vec r_1, \vec r_2)$ basis. Thus, the solution was to find largest $g$ which divides every point $a_k$. This can be done with Euclidean algorithm. Similar idea applies to this problem except for rotations in $3$-dimensional case are represented with quaternions rather than complex numbers. You may get some basic notion of quaternions from this article. Note that in $3$-dimensional space if integer vectors $\vec r_1$, $\vec r_2$ and $\vec r_3$ are pairwise orthogonal and have the same length, then their length is an integer number as well. This is due to the fact that $\vec r_3$ may be represented explicitly in the following form: $\vec r_3 = \pm\frac{\vec r_1 \times \vec r_2}{|r_1|}$ We should note here that both $\vec r_3$ and $\vec r_1 \times \vec r_2$ have integer coordinates, thus $|r_1|$ is rational. But since $|r_1|^2$ is integer, we may conclude that $|r_1|$ is integer as well. This brings us to the conclusion that vectors $\frac{\vec r_1}{|\vec r_1|}$, $\frac{\vec r_2}{|\vec r_2|}$ and $\frac{\vec r_3}{|\vec r_3|}$ have rational coordinates, thus the transformation which maps basis vectors $\vec e_x$, $\vec e_y$ and $\vec e_z$ into $\vec r_1$, $\vec r_2$ and $\vec r_3$ may be represented as the combination of rational rotation and scaling, that is: $\vec v \mapsto k \cdot \frac{q \cdot \vec v \cdot \bar q}{q \cdot \bar q}$ Here $q = s + ix + jy + kz$ is an integer quaternion representing the rotation, $\bar q = s - ix - jy - kz$ is its conjugate quaternion, and $k=r$ is some integer scaling factor. If we write this transform explicitly in matrix form, its matrix will be as follows: $\frac{k}{s^2+x^2+y^2+z^2} \cdot \begin{pmatrix} s^2+x^2-y^2-z^2 & 2xy-2sz & 2xz+2sy \\ 2xy+2sz & s^2-x^2+y^2-z^2 & 2yz-2sx \\ 2xz-2sy & 2yz+2sx & s^2-x^2-y^2+z^2 \end{pmatrix}$ Since this transform maps $\vec e_x$, $\vec e_y$ and $\vec e_z$ to integer vectors $\vec r_1$, $\vec r_2$ and $\vec r_3$, all matrix elements should be integer. That is, if we reduce the fraction $\frac{k}{s^2+x^2+y^2+z^2}$, its denominator should divide every matrix element. Without loss of generality we may assume that $\gcd(s,x,y,z)=1$, because otherwise we may simply reduce all quaternion coordinates by this common divisor and matrix elements will stay same. Now if $\frac{k}{s^2+x^2+y^2+z^2}=\frac{P}{Q}$ then $Q$ should divide every element of the matrix and it also should divide $s^2+x^2+y^2+z^2$. Thus, it divides: $\gcd\begin{pmatrix} s^2+x^2+y^2+z^2\\ s^2+x^2-y^2-z^2\\ s^2-x^2+y^2-z^2\\ s^2-x^2-y^2+z^2 \end{pmatrix}=\gcd\begin{pmatrix} s^2+x^2+y^2+z^2\\ 2(y^2+z^2)\\ 2(x^2+z^2)\\ 2(x^2+y^2) \end{pmatrix}=\gcd\begin{pmatrix} s^2+x^2+y^2+z^2\\ 2(y^2+z^2)\\ 2(x^2+z^2)\\ 4z^2 \end{pmatrix}$ Here we utilized the fact that $\gcd(a\pm b, b)=\gcd(a, b)=\gcd(-a,b)$. Next thing to note is that $\gcd(a, b)$ always divides $\gcd(k\cdot a, b)$, thus $Q$ should divide: $\gcd\begin{pmatrix} 4(s^2+x^2+y^2+z^2)\\ 4(y^2+z^2)\\ 4(x^2+z^2)\\ 4z^2 \end{pmatrix}=4\gcd(s^2,x^2,y^2,z^2)=4$ Which means that every transform we're looking for may be represented in the following form: $\vec v \mapsto \frac{k}{4} \cdot q \cdot \vec v \cdot \bar q$ Where $q$ is some integer quaternion with $\gcd(s,x,y,z)=1$ and $k$ is some integer scaling factor. Quaternions having all integer components are called Lipschitz quaternions. But in this problem we will need to find greatest common divisor of some quaternions and using Lipschitz quaternions won't be enough for us because they don't form an Euclidean domain. Instead, we'll stick to Hurwitz quaternions in which it's also allowed for quaternion to have all of its coordinates semi-integer. With such quaternions we may further divide quaternion by $2$ if all its components are odd, which will reduce the set of possible denominators to $\{1,2\}$ only, thus in Hurwitz quaternions any transform may be represented as: $\vec v \mapsto \frac{k}{2} \cdot q \cdot \vec v \cdot \bar q$ Now, given this knowledge, we have to find a Hurwitz quaternion $q$ and scaling factor $k$ such that every point from the set $A$ is the image of some integer vector under this transform. Basically, we assume here that $\vec r_1$, $\vec r_2$ and $\vec r_3$ are images of unit basis vectors $\vec e_x$, $\vec e_y$ and $\vec e_z$. If this is true, then $a_k = u_k \cdot \vec r_1 + v_k \cdot \vec r_2 + w_k \cdot \vec r_3$ is the image of the vector $b_k$ defined as $b_k = u_k \cdot \vec e_x + v_k \cdot \vec e_y + w_k \cdot \vec e_z$. For simplicity we will further work with vectors $a_i$ multiplied by $2$, as in this way we may safely assume that they were obtained with $v \mapsto k \cdot q \cdot \vec v \cdot \bar q$ mapping. Now we should further work with the quaternion $g=\gcd(a_1,\dots,a_n)$ which is obtained as GCD of input vectors as if they were Hurwitz quaternions and with the number $G=\gcd(\|a_1\|,\dots,\|a_n\|)$, where $\|q\|=q\cdot\bar q = s^2+x^2+y^2+z^2$ is the norm of $q$. Among major properties of quaternionic norm we should note that it's multiplicative, that is $\|a\cdot b\| =\|a\| \cdot \|b\|$. Due to this we may conclude that $\|k\|\cdot \|q\|^2=k^2 \|q\|^2$ should always divide $G$. Thus with the number $G$ fixed there may only be at most $O(G^{1/6})$ possible values of $\|q\|$ which may be found in $O(G^{1/3})$ because if $a^2$ divides $b$ then either $a$ or $b/a$ is at most $b^{1/3}$. In our problem $G$ may only be up to $10^{16}$, which makes it up to nearly $500$ candidate numbers for being equal to $\|q\|$ which may be found in $\approx 2.5\cdot 10^5$ arithmetic operations. Now to check if it's possible to obtain $q$ with $\|q\|$ being fixed we should look on the quaternion $g$. Under given constraints $g$ is primitive (not divisible by any integer constant larger than $1$). It may be proven thus that if $g$ is primitive and $\|g\|=ab$ then $g$ may be uniquely (up to units) represented as $g=qp$ where $\|q\|=a$ and $\|p\|=b$. Due to this if we fix $\|q\|$ we may find actual $q$ as $\gcd(g,\|q\|)$ because $q\bar q =\|q\|$. After this we only have to check if this $q$ actually produces all points from the input set, which may be done in $O(n)$. Therefore, the total complexity of described solution is $O(G^{1/3}+G^{1/6}n)$.
[ "geometry", "math", "matrices", "number theory" ]
3,500
null
1379
A
Acacius and String
Acacius is studying strings theory. Today he came with the following problem. You are given a string $s$ of length $n$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once? Each question mark should be replaced with \textbf{exactly one} lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc". Occurrence of a string $t$ of length $m$ in the string $s$ of length $n$ as a substring is a index $i$ ($1 \leq i \leq n - m + 1$) such that string $s[i..i+m-1]$ consisting of $m$ consecutive symbols of $s$ starting from $i$-th equals to string $t$. For example string "ababa" has two occurrences of a string "aba" as a substring with $i = 1$ and $i = 3$, but there are no occurrences of a string "aba" in the string "acba" as a substring. Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string \textbf{exactly once}.
At first, we will check if some string of length $n$ contains exactly one occurrence of "abacaba". Lemma 1. This check can be done in $O(n)$ time. Proof. We can try all the possible positions $i$ of a string $s$ and check whether $i$ is a starting position for a substring "abacaba". This check can be performed in a $O(1)$ time by checking if $s_{i + j} = t_j$ for all $j \in [0; 6]$ where string $t$ is "abacaba". So, overall complexity of such a check works in $n \cdot O(1) = O(n)$ time. To solve the problem we will iterate over all positions $i$ and check whether there exists a valid string such that its single occurrence of a substring "abacaba" starts from position $i$. String $s$ has a single occurrence $i$ of a substring "abacaba" if and only if two following criteria are satisfied. $i$ is a occurrence of a substring "abacaba" in $s$. There are no occurrence $j$ of a substring "abacaba" in $s$ such that $i \neq j$. First criterion can be checked directly. $i$ can be an occurrence of a substring "abacaba" in a resulting string if and only if for all $j \in [0; 6]$ $s_{i + j} = t_j$ or $s_{i + j} = '?'$. To check the second criterion we need the following lemma. Lemma 2. Question marks in string $s$ can be replaced with lowercase English letters in such a way that no new occurrences of "abacaba" will appear. Proof. Let's replace all the questing marks with "z" letter. Any substring of $s$ that contained question mark will not become a occurrence of "abacaba" since "abacaba" does not contain "z". So after fixing position of a single occurrence $i$ resulting string can be constructed directly. This leads to a $O(n^2)$ solution. Refer to author's solution code for more details.
[ "brute force", "implementation", "strings" ]
1,500
#include <bits/stdc++.h> using ll = long long; using ld = long double; using ull = unsigned long long; using namespace std; const string T = "abacaba"; int count(const string& s) { int cnt = 0; for (int i = 0; i < (int)s.size(); ++i) { if (s.substr(i, T.size()) == T) { ++cnt; } } return cnt; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; for (int tt = 1; tt <= t; ++tt) { int n; cin >> n; string s; cin >> s; bool F = false; for (int i = 0; i + T.size() <= n; ++i) { string ss = s; bool ok = true; for (int j = 0; j < T.size(); j++) { if (ss[i + j] != '?' && ss[i + j] != T[j]) { ok = false; break; } ss[i + j] = T[j]; } if (ok && count(ss) == 1) { for (int j = 0; j < n; j++) { if (ss[j] == '?') { ss[j] = 'd'; } } F = true; cout << "Yes\n"; cout << ss << "\n"; break; } } if (!F) { cout << "No\n"; } } return 0; }
1379
B
Dubious Cyrpto
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $n$, he encrypts it in the following way: he picks three integers $a$, $b$ and $c$ such that $l \leq a,b,c \leq r$, and then he computes the encrypted value $m = n \cdot a + b - c$. Unfortunately, an adversary intercepted the values $l$, $r$ and $m$. Is it possible to recover the original values of $a$, $b$ and $c$ from this information? More formally, you are asked to find any values of $a$, $b$ and $c$ such that - $a$, $b$ and $c$ are integers, - $l \leq a, b, c \leq r$, - there exists a strictly positive integer $n$, such that $n \cdot a + b - c = m$.
The task is to solve equation $n\cdot a + b - c = m$ in integers, where $n$ - is some natural number, and $a, b, c \in [l; r]$. Note that the expression $b - c$ can take any value from $[l-r; r-l]$ and only these values. Indeed, if $0 \leq x \leq r-l$, then if we denote $b = x + l$, $c = l$, we get $b - c = x$. A similar statement is true for $l - r \leq x \leq 0$. So, since it was necessary to solve the equation $n\cdot a + b - c = m$, this is equivalent to solving the equation $n \cdot a \in [m - (r - l); m + (r - l)]$, where $a \in [l; r]$, $n \in \mathbb N$. Let's fix some arbitrary $a$. Then we find the maximum $n$ for which $n\cdot a \leq m + (r - l)$ - this $n$ will be equal to $n' = \lfloor \frac{m + r - l}{a} \rfloor$. Let's check whether it is true that $n' > 0$ and $n' \cdot a \in [m- (r-l); m + (r - l)]$. If this is the case, then restore $b$ and $c$ as indicated above. This solution iterates over all possible values of $a$, and checks if such $a$ can be used in answer if the manner described above. Thus, this solution has complexity $\mathcal O (r - l)$
[ "binary search", "brute force", "math", "number theory" ]
1,500
null
1379
C
Choosing flowers
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her \textbf{exactly} $n$ flowers. Vladimir went to a flower shop, and he was amazed to see that there are $m$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $i$-th type happiness of his wife increases by $a_i$ and after receiving each consecutive flower of this type her happiness increases by $b_i$. That is, if among the chosen flowers there are $x_i > 0$ flowers of type $i$, his wife gets $a_i + (x_i - 1) \cdot b_i$ additional happiness (and if there are no flowers of type $i$, she gets nothing for this particular type). Please help Vladimir to choose exactly $n$ flowers to maximize the total happiness of his wife.
Let's look at sorts, for which there is more than one flower in the bouquet. We can prove, that there can be only one such sort. Let's assume that there are sorts $x$ and $y$ with $b_x \ge b_y$, such that for both sorts there are at least 2 flowers. Let's exclude flower of sort $y$ from bouquet and add flower of sort $x$. The total happiness will change by $b_x - b_y$, so it will not decrease. Repeating this, we can leave bouquet with only one flower of sort $y$ without decreasing the total happiness. So, there always exists an answer where there is only one sort with multiple flowers. Using this fact, we can solve the problem the following way. Let's iterate over each sort of flowers and for every $x$ suppose that there are multiple flowers of sort $x$. It is obvious, that if some sort $y$ has $a_y > b_x$, then we should take one flower of such sort, and if $a_y \le b_x$, then we would better take another flower of sort $x$. So, we need to know sum of $a_i$ for all flowers that have $a_i > b_x$. To do it in $O(\log m)$, we can sort all flowers by $a_y$ in decreasing order, calculate prefix sums on that array, and using binary search find maximum $k$, such that $a_k > b_x$ and get prefix sum of $a_i$ for first $k$ sorts. All the rest $n - k$ flowers will be of the sort $x$. Also we should take into account the case when for each sort only one flower of that sort is taken. In that case we should take $n$ sorts with largest $a_i$. That way we can get the answer in $O(m \log m)$ time.
[ "binary search", "brute force", "data structures", "dfs and similar", "dp", "greedy", "sortings", "two pointers" ]
2,000
null
1379
D
New Passenger Trams
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of $h$ hours, and each hour consists of $m$ minutes, where $m$ is an even number. Currently, there are $n$ freight trains, and they depart every day at the same time: $i$-th train departs at $h_i$ hours and $m_i$ minutes. The government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at $0$ hours and $t$ minutes, where $0 \le t < {m \over 2}$, the second tram departs $m \over 2$ minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement. To allow passengers to board the tram safely, the tram must arrive $k$ minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at $0$ hours and $t$ minutes, where $t < k$, then the freight trains can not depart during the last $k - t$ minutes of the day. \begin{center} {\small A schematic picture of the correct way to run passenger trams. Here $h=2$ (therefore, the number of passenger trams is $2h=4$), the number of freight trains is $n=6$. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length $k$ before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments.} \end{center} Unfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of $t$ to minimize the number of canceled freight trains in case all passenger trams depart according to schedule.
Let's look what happens if we fix $t$ for answer. Start time leads to canceling every train, which has $m_i$ in one of ranges $[t - k + 1, t - 1],\ [t + \frac{m}{2} - k + 1, t + \frac{m}{2} - 1]$. Some borders may be either negative or greater than $m$, but values must be count modulo $m$. We may imagine them as segments on a circle with length m. Now let's look at every train. If train departs at $m_i$ then it must be canceled if we choose $t$ in segments $[m_i + 1, m_i + k - 1],\ [m_i + \frac{m}{2} + 1, m_i + \frac{m}{2} + k - 1]$. Otherwise it shouldn't be canceled. So, we need to find such point $t$ in $[0, \frac{m}{2} - 1]$, that $t$ is covered by minimal number of segments. Note that we block two simmetrical segments - difference between their borders is equal to half of circle's length. Cause we need only segments in first half of the cycle, we can look at these segments modulo $\frac{m}{2}$, where they collapse into one segment. Now we need to sort segment's borders. Segments are placed on circle, so some of them should be split in two - one ends in $\frac{m}{2} - 1$, another starts at $0$. Now we need to find point, which is covered by minimal number of segments. For that we will keep a variable counting current number of open segments, and change it from one coordinate to another. We can skip coordinates with no events on them, so all solution will take $O(n \log n)$ time to solve.
[ "binary search", "brute force", "data structures", "sortings", "two pointers" ]
2,300
null
1379
E
Inverse Genealogy
Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in this structure are conveniently numbered from $1$ to $n$, and $s_i$ denotes the child of the person $i$ (and $s_i = 0$ for exactly one person who does not have any children). We say that $a$ is an ancestor of $b$ if either $a = b$, or $a$ has a child, who is an ancestor of $b$. That is $a$ is an ancestor for $a$, $s_a$, $s_{s_a}$, etc. We say that person $i$ is imbalanced in case this person has both parents specified, and the total number of ancestors of one of the parents is at least double the other. Ivan counted the number of imbalanced people in the structure, and got $k$ people in total. However, he is not sure whether he computed it correctly, and would like to check if there is at least one construction with $n$ people that have $k$ imbalanced people in total. Please help him to find one such construction, or determine if it does not exist.
Let's rephrase the statement. Critical node - a non-leaf node with subtrees, where one $2$ or more times smaller than another. We need to find an example of the binary tree with $n$ nodes there $k$ of them are critical. First of all, let's count number of nodes if we know that there $m$ leafs. Because of the fact, that tree is binary, size of the tree should be $2m - 1$. So for even $n$ there is no answer. A number of critical nodes can't be more than $max\left(0, \frac{n - 3}{2}\right)$. It is obvious that caterpillar tree have maximum number of critical nodes. Let's say that $n$ is almost a power of two then $n + 1$ is a power of two. If there $0$ critical nodes, then $n$ is almost a power of two (example full binary tree). Suppose exist trees that don't satisfy the condition. Let's look on the smallest one. Left and right subtrees satisfy the condition. If they are different, then one of them $2$ times bigger than another and root is critical. If they are have equal sizes, then our tree satisfied the condition. If there $1$ critical nodes, then $n$ isn't almost a power of two. Suppose there exist trees that don't satisfy the condition. Let's look on the smallest one. One of the subtrees is almost a power of two. If both subtrees are almost a power of two, then they are equal and there is no critical nodes. In other case, the root isn't critical. Then second subtree isn't almost a power of two. If we write two inequalities with the size of the tree and the size of the first subtree, then it becomes clear that size of the tree can't be almost a power of two. How to construct an example with $1$ critical node? Let $m$ be some integer that: $2^m < n < 2^{m + 1}$. It can be shown that one subtree in answer can be equals $2^{m} - 1$ or $2^{m - 1} - 1$. And finally, what we should do when $k \geq 2$? Let's go from $(n, k)$ to $(n - 2, k - 1)$. If $n \geq 13$ we can just make one subtree size of $1$. In other cases we should precalculate answers. So we have solution with complexity $O(n)$. The easy way to write a solution is make a function $can(n, k)$ that return True if there exists needed tree and else False. Then we can find the smallest subtree with simple brute force. In this case complexity is $O(n \log n)$.
[ "constructive algorithms", "divide and conquer", "dp", "math", "trees" ]
2,800
null
1379
F1
Chess Strikes Back (easy version)
\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.} Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard $2n \times 2m$: it has $2n$ rows, $2m$ columns, and the cell in row $i$ and column $j$ is colored white if $i+j$ is even, and is colored black otherwise. The game proceeds as follows: Ildar marks some of the \textbf{white} cells of the chessboard as unavailable, and asks Ivan to place $n \times m$ kings on the remaining \textbf{white} cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner. Ildar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has $q$ queries. In each query he marks a cell as unavailable. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!
Let's divide the grid into $nm$ squares of size $2 \times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-square $(x_1, y_1)$ and R-square $(x_2, y_2)$, such that: $x_1 \leq x_2$ $y_1 \leq y_2$ the answer is NO. It's easy to prove because if such pair of cells exists we can consider path from $(x_1, y_1)$ to $(x_2, y_2)$. In this path, there will be two neighboring cells. If no such pairs of cells exist the answer is YES. Note that in this version of the problem cells cannot become available againg. This means that for some prefix of queries the answer is YES and for the remaining suffix the answer is NO. Let's do a binary search to find position of the last YES. How to check that the answer is YES fast enough? Let's calculate the values: $a_x =$ minimal $y$, such that $(x, y)$ is L-square $b_x =$ maximal $y$, such that $(x - 1, y)$ is R-square After that, we should check, that $a_i > b_j$ for all $i > j$. We can easily do this using prefix maximums for $a$ and suffix minimums for $b$ Total complexity is $O((n+q) \log{q})$.
[ "binary search", "data structures" ]
2,700
null
1379
F2
Chess Strikes Back (hard version)
\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.} Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard $2n \times 2m$: it has $2n$ rows, $2m$ columns, and the cell in row $i$ and column $j$ is colored white if $i+j$ is even, and is colored black otherwise. The game proceeds as follows: Ildar marks some of the \textbf{white} cells of the chessboard as unavailable, and asks Ivan to place $n \times m$ kings on the remaining \textbf{white} cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner. Ildar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has $q$ queries. In each query he either marks a cell as unavailable, or marks the previously unavailable cell as available. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!
Let's divide the grid into $nm$ squares of size $2 \times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-square $(x_1, y_1)$ and R-square $(x_2, y_2)$, such that: $x_1 \leq x_2$ $y_1 \leq y_2$ the answer is NO. It's easy to prove because if such pair of cells exists we can consider path from $(x_1, y_1)$ to $(x_2, y_2)$. In this path, there will be two neighboring cells. If no such pairs of cells exist the answer is YES. So, after each query, we should check this condition. Let's maintain the values: $a_x =$ minimal $y$, such that $(x, y)$ is L-square $b_x =$ maximal $y$, such that $(x - 1, y)$ is R-square These values can be maintained using $O(n)$ sets in $O(\log{q})$ time. After that, we should check, that $a_i > b_j$ for all $i > j$. Let's make a segment tree with values: minimal $a_i$ on segment maximal $b_i$ on segment the flag, that for all $i > j$ from the segment it is true, that $a_i > b_j$ It is easy to merge two such segments, to calculate the flag, we should check, that $min_{left} > max_{right}$. So, the total time to answer the query is $O(\log{n}+\log{q})$. Total complexity is $O((n+q)(\log{n}+\log{q}))$.
[ "data structures", "divide and conquer" ]
2,800
null
1380
A
Three Indices
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once. Find three indices $i$, $j$ and $k$ such that: - $1 \le i < j < k \le n$; - $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices.
A solution in $O(n^2)$: iterate on $j$, check that there exists an element lower than $a_j$ to the left of it, and check that there exists an element lower than $a_j$ to the right of it. Can be optimized to $O(n)$ with prefix/suffix minima. A solution in $O(n)$: note that if there is some answer, we can find an index $j$ such that $a_{j - 1} < a_j$ and $a_j > a_{j + 1}$ (if there is no such triple, the array descends to some point and ascends after that, so there is no answer). So we only have to check $n - 2$ consecutive triples.
[ "brute force", "data structures" ]
900
#include <bits/stdc++.h> using namespace std; const int N = 1000; int n; int a[N]; void solve() { cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 1; i < n - 1; ++i) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { cout << "YES" << endl; cout << i << ' ' << i + 1 << ' ' << i + 2 << endl; return; } } cout << "NO" << endl; } int main() { int T; cin >> T; while (T--) solve(); }
1380
B
Universal Solution
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $s = s_1 s_2 \dots s_{n}$ of length $n$ where each letter is either R, S or P. While initializing, the bot is choosing a starting index $pos$ ($1 \le pos \le n$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $s_{pos}$: - if $s_{pos}$ is equal to R the bot chooses "Rock"; - if $s_{pos}$ is equal to S the bot chooses "Scissors"; - if $s_{pos}$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $s_{pos + 1}$. In the third round — on $s_{pos + 2}$ and so on. After $s_n$ the bot returns to $s_1$ and continues his game. You plan to play $n$ rounds and you've already figured out the string $s$ but still don't know what is the starting index $pos$. But since the bot's tactic is so boring, you've decided to find $n$ choices to each round to maximize the average number of wins. In other words, let's suggest your choices are $c_1 c_2 \dots c_n$ and if the bot starts from index $pos$ then you'll win in $win(pos)$ rounds. Find $c_1 c_2 \dots c_n$ such that $\frac{win(1) + win(2) + \dots + win(n)}{n}$ is maximum possible.
Let's look at the contribution of each choice $c_i$ to the total number of wins $win(1) + win(2) + \dots + win(n)$ (we can look at "total" instead of "average", since "average" is equal to "total" divided by $n$). For example, let's look at the first choice $c_1$: in $win(1)$ we compare $c_1$ with $s_1$, in $win(2)$ - $c_1$ with $s_2$, in $win(3)$ - $c_1$ with $s_3$ and so on. In the result, we compare $c_1$ with all $s_i$ once. So, to maximize the total sum, we need to choose $c_1$ that beats the maximum number of $s_i$ or, in other words, let's find the most frequent character in $s$ and choose $c_1$ that beats it. Okay, we found the optimal $c_1$. But if we look at the contribution of any other $c_i$ we can note that we compare any $c_i$ with all $s_i$ once. So we can choose all $c_i$ equal to $c_1$ which is equal to the choice that beats the most frequent choice in $s$.
[ "greedy" ]
1,400
fun main() { val winBy = mapOf('R' to 'P', 'S' to 'R', 'P' to 'S') repeat(readLine()!!.toInt()) { val s = readLine()!! val maxCnt = s.groupingBy { it }.eachCount().maxBy { it.value }!!.key println("${winBy[maxCnt]}".repeat(s.length)) } }
1380
C
Create The Teams
There are $n$ programmers that you want to split into several non-empty teams. The skill of the $i$-th programmer is $a_i$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $x$. Each programmer should belong to at most one team. Some programmers may be left without a team. Calculate the maximum number of teams that you can assemble.
At first, notice that if only $k < n$ programmers are taken, then the same or even better answer can be achieved if $k$ strongest programmers are taken. Now let's sort the programmers in a non-increasing order and choose some assignment into the teams. For each team only the rightmost taken programmer of that team matters (the sorted sequence implies that the rightmost is the weakest). Take a look at the team with the strongest weakest member. If the number of programmers in it is less than the position of the weakest member, then you can safely rearrange the programmers before him in such a way that none of parameters of later teams change and the weakest member in the first one only becomes stronger. After that you can get rid of the first team (as it takes exactly the prefix of all the programmers) and proceed to fix the later teams. Thus, we can see that there is an optimal solution such that each team is a segment and all the teams together take some prefix of the programmers. So we can finally run a greedy solution that takes programmers from left to right and increases the answer if the conditions for the latest team hold. Overall complexity: $O(n \log n)$.
[ "brute force", "dp", "greedy", "implementation", "sortings" ]
1,400
for _ in range(int(input())): n, x = map(int, input().split()) a = sorted(list(map(int, input().split())), reverse=True) res, cur = 0, 1 for s in a: if s * cur >= x: res += 1 cur = 0 cur += 1 print(res)
1380
D
Berserk And Fireball
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct. You have two types of spells which you may cast: - Fireball: you spend $x$ mana and destroy \textbf{exactly} $k$ consecutive warriors; - Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$. You want to turn the current sequence of warriors powers $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$. Calculate the minimum amount of mana you need to spend on it.
The first thing we need to do is to find the occurrences of $b_i$ in the sequence $[a_1, a_2, \dots, a_n]$ - these are the monsters that have to remain. Since both spells (Fireball and Berserk) affect consecutive monsters, we should treat each subsegment of monsters we have to delete separately. Consider a segment with $x$ monsters we have to delete such that the last monster before it has power $l$, the first monster after the segment has power $r$, and the strongest monster on the segment has power $p$. If $x \bmod k \ne 0$, then we have to use Berserk at least $x \bmod k$ times. Let's make the strongest monster on segment kill some other monster. If $x < k$, then the strongest monster should also be killed by one of the monsters bounding the segment, so if $l < p$ and $r < p$, there is no solution. Okay, now the number of monsters is divisible by $k$. If it is more profitable to use Fireball, we use the required number of Fireballs to kill all of them. Otherwise, we have to kill the maximum possible number of monsters with Berserk and finish the remaining ones with Fireball. If $l > p$ or $r > p$, then one of the monsters just outside the segment can kill all the monsters inside the segment; otherwise, the strongest monster should kill adjacent monsters until exactly $k$ remain, and those $k$ monsters are finished with a single Fireball. Now we know what we need to consider when processing a single segment; all that's left is to sum the minimum required mana over all such segments. Since the total length of these segments is at most $n - 1$ and we can process each segment in linear time, we have a solution with complexity $O(n)$.
[ "constructive algorithms", "greedy", "implementation", "math", "two pointers" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n, m; long long x, k, y; int a[N]; int b[N]; bool upd(int l, int r, long long &res) { if (l > r) return true; bool canDel = false; int mx = *max_element(a + l, a + r + 1); int len = r - l + 1; if (l - 1 >= 0 && a[l - 1] > mx) canDel = true; if (r + 1 < n && a[r + 1] > mx) canDel = true; if (len < k && !canDel) return false; int need = len % k; res += need * y; len -= need; if (y * k >= x) { res += len / k * x; } else if(canDel) { res += len * y; } else { res += (len - k) * y + x; } return true; } int main(){ scanf("%d %d", &n, &m); scanf("%lld %lld %lld", &x, &k, &y); for (int i = 0; i < n; ++i) scanf("%d", a + i); for (int i = 0; i < m; ++i) scanf("%d", b + i); long long res = 0; int lst = -1, posa = 0, posb = 0; while (posb < m) { while(posa < n && a[posa] != b[posb]) ++posa; if (posa == n) { puts("-1"); return 0; } if (!upd(lst + 1, posa - 1, res)) { puts("-1"); return 0; } lst = posa; ++posb; } if (!upd(lst + 1, n - 1, res)) { puts("-1"); return 0; } printf("%lld\n", res); return 0; }