| Predictor | A | B | C | D1 | D2 | E | F1 | F2 | G | H |
|---|---|---|---|---|---|---|---|---|---|---|
| Predicted | 486 | 927 | 839 | 1160 | 2236 | 1694 | 2406 | 3639 | 2607 | 3250 |
| nifeshe | 800 | 900 | 1100 | 1400 | 2600 | 2000 | 2500 | 3500 | 2900 | 3400 |
| ttamx | 800 | 1000 | 1200 | 1400 | 2500 | 1800 | 2100 | 3500 | 2800 | 3100 |
| ItzsleepyXD | ? | ? | 1000 | ? | ? | ? | 2100 | 2800 | ? | ? |
| simplelife | 800 | 1000 | 1100 | 1500 | ? | 1900 | 2300 | 3500 | ? | 3000 |
| wakanda-forever | 900 | 1000 | 1100 | ? | ? | 2000 | 2100 | ? | ? | ? |
| Marszpace | 800 | 1000 | 1100 | 1500 | ? | 1900 | ~2200 | ? | ? | ? |
| Argentum47 | 800 | 1200 | 1200 | 1600 | ? | 1900 | 2300 | ? | ? | 2700 |
| omsincoconut | 800 | 1100 | 1300 | ? | ? | ? | 2400 | 3500 | 2600 | 3100 |
| Stathis | 900 | 1200 | 1300 | 1600 | 2700 | 1800 | 2200 | 3500 | 2600 | 2800 |
| ReverseFlash081 | 900 | 1100 | 1100 | 1400 | 2500 | 1900 | ? | ? | ? | ? |
| samsoom | 800 | 1000 | 1100 | 1400 | 2300 | 1800 | ? | ? | ? | ? |
| SkyMagic | 800 | 900 | 1000 | ? | ? | 1500 | ? | ? | 800 | 3100 |
| nik_exists | 800 | 1000 | 1000 | ? | ? | 1700 | ? | ? | ? | ? |
| yse | 800 | 900 | 1000 | 1200 | 2200 | 1900 | 2500 | 3400 | 2900 | 3200 |
| Proof_by_QED | 800 | 900 | 1000 | 1400 | 2500 | 2100 | 2600 | 3500 | 2900 | 3100 |
2261A - Hey, It's Me, Souvlakity
Author: SpyrosAliv
Preparation, Editorial: Marszpace
The number of integers Souvlakity initially has is the same as the number of integers he has at the end of the game.
Consider cases based on the amount of integers Souvlakity has.
The number of integers Souvlakity initially owns is equal to the number of integers he owns at the end of the game. This is because during each pair of consecutive turns (Souvlakity's turn and then Kalamakity's turn), Souvlakity gives away exactly one integer but also receives exactly one integer.
Let $$$k$$$ be the number of integers that Souvlakity owns at the beginning of the game.
If $$$k=1$$$, Souvlakity will own a single integer at the end of the game, so his score is $$$0$$$.
If $$$k=2$$$, no matter which integer Souvlakity chooses to give away in round 1, Kalamakity can give him an integer adjacent to the one he kept. His score is $$$1$$$, and Kalamakity can force this score at the end of the game by always giving Souvlakity the same integer back.
If $$$k\ge3$$$, Souvlakity can give away any integer that is not his minimum or maximum, and his score does not decrease. Kalamakity can also keep returning the integer that Souvlakity just gave him, and therefore Souvlakity's score does not increase. At the end, Souvlakity will have the same maximum and minimum as he did at the beginning of the game, with the score of $$$\max(S)-\min(S)$$$.
Therefore we only need to find $$$k$$$, $$$\max(S)$$$ and $$$\min(S)$$$ which is doable in $$$O(n)$$$.
#include <bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
string s;
cin >> n >> s;
int c = count(s.begin(), s.end(), '1');
if (c <= 2) {
cout << c-1 << '\n';
continue;
}
int l = s.find('1'), r = s.rfind('1');
cout << r-l << '\n';
}
}
2261B - What's the Capital of France?
Author, Preparation, Editorial: omsincoconut
What is the maximum possible answer?
Only the minimum and maximum value in the array matters.
Think about solving from the highest bit.
Denote $$$\operatorname{msb}(x)$$$ as the position of the most significant bit of $$$x$$$, where the $$$0$$$-th bit is the least significant bit.
The maximum value cannot increase, so $$$\operatorname{msb}(answer) = \operatorname{msb}(\max(a)) = b$$$.
If $$$\operatorname{msb}(\min(a)) \lt b$$$, then we can increase the minimum value to be $$$2^b - 1$$$ by repeatedly incrementing some entry in the array that is adjacent to a larger entry and less than $$$2^b - 1$$$. This results in the answer being exactly $$$2^{b+1} - 1$$$.
What if $$$\operatorname{msb}(\min(a)) = b$$$ though? Then we cannot do anything to that bit or the bits higher. We can just ignore the $$$\operatorname{msb}$$$ bit and all higher bits. Repeat this until the bit of the maximum and minimum entries of the array does not match.
Hence, the answer is $$$\max(a) \operatorname{OR}(2^{k+1} - 1)$$$ where $$$k = \operatorname{msb}(\max(a) \operatorname{XOR} \min(a))$$$ if $$$\max(a) \neq \min(a)$$$, and simply $$$\max(a)$$$ otherwise.
#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t;cin>>t;
while(t--) {
int n;cin>>n;
int mx=INT_MIN,mn=INT_MAX;
for (int i = 0; i < n; i++) {
int a;cin >> a;
mx = max(mx,a);
mn = min(mn,a);
}
if (mx == mn) cout << mx << '\n';
else {
cout << (((1<<(32-__builtin_clz(mx^mn)))-1)|mx) << '\n';
}
}
}
2261C - I Know About a Million Things
Author, Preparation, Editorial: Marszpace
For each state, does the actual value of the integers in the array matter? What matters for each state?
Only the counts of odd and even integers matter. In which state can Larpity win?
Consider states you know Larpity (as the second player) win. Think how Moggity (as the first player) can give Larpity that first-player-losing state.
Only the counts of odd and even integers matter, not the values themselves, because whether a move can be done is based on the parity of their sum, and that parity only depends on the parity of the elements. Therefore, we can represent every input (and game state) with $$$(E,O)$$$, where $$$E$$$ is the number of even integers and $$$O$$$ is the number of odd integers.
Firstly, we can observe that Larpity wins when the input is in state $$$(1,1)$$$ or $$$(0,3)$$$. Here's why:
- For $$$(1,1)$$$ (for example, the integers $$$2,3$$$, as given in one of the samples), Moggity cannot remove both of the integers, and he must remove one. Larpity removes the remaining one, and Moggity faces an empty array.
- For $$$(0,3)$$$ (for example, the integers $$$1,3,5$$$), Moggity cannot remove all three of the integers. If he removes one integer, Larpity can remove the other two, and Moggity faces an empty array. If he removes two integers, Larpity can remove the other one, and Moggity once again faces an empty array.
Therefore, for these two cases, Larpity wins.
Then, we will show that, in any other cases, Moggity will win.
- Consider the case where $$$O$$$ is even (including $$$O=0$$$), i.e. there is an even number of odd integers. The sum over the entire array is even, so Moggity can remove the entire array and win on the first turn.
- Consider the case where $$$O$$$ is $$$1$$$. If $$$E$$$ is $$$0$$$, then Moggity can remove the single odd integer and win. If $$$E$$$ is $$$1$$$, this is the state $$$(1,1)$$$ where Moggity loses. If $$$E\geq2$$$, Moggity can remove $$$E-1$$$ even integers, and force Larpity to face the state $$$(1,1)$$$. Larpity must remove one integer, and cannot remove two, and so Larpity will lose, and Moggity will win.
- Consider the case where $$$O$$$ is $$$3$$$. If $$$E$$$ is $$$0$$$, we know Moggity loses. If $$$E\geq1$$$, Moggity can remove all even integers, and again, force Larpity to face a losing position of $$$(0,3)$$$. Larpity must remove one or two integers, and cannot remove three, so Larpity will lose, and once again Moggity will win.
- Consider the case when $$$O$$$ is odd and $$$O\geq 5$$$, Moggity can remove all even integers (if any), and $$$O-3$$$ odd integers. This leaves Larpity with the state of $$$(0,3)$$$, and once again, Larpity will lose.
Thus, Larpity wins if and only if the array is exactly one odd and one even integer, or exactly three odd integers (i.e. $$$(E,O)=(1,1)$$$ or $$$(0,3)$$$) and Moggity wins in all other cases.
The total time complexity is $$$O(n)$$$ for scanning over all elements and counting the odd and even elements.
/*
* And in that light, I find deliverance.
* TASK : WorldQuant Round 1 : I Know A Million Things (feat. Gessou by Chroma and rintaro soma, from CHUNITHM)
* AUTHOR : Marszpace
*/
#include<bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
int cnt[2]={};
for(int i=0;i<n;i++){
int a;
cin >> a;
cnt[a%2]++;
}
if((cnt[1]==1 && cnt[0]==1) || (cnt[1]==3 && cnt[0]==0)){
cout << "Larpity\n";
return;
}
cout << "Moggity\n";
return;
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int tt;
cin >> tt;
while(tt--){
solve();
}
return 0;
}
2261D1 - Come Be My Friend, Don't Be So Scared (Easy Version)
Author, Preparation: omsincoconut Editorial:Proof_by_QED
All the spots being distinguishable means that the reports for any two spots are different from at least one detector.
Each detector is an interval. It can only change in two endpoints. Come up with a lower bound for $$$k$$$ from this, and then come up with a construction that achieves this lower bound.
Since $$$m=0$$$, there are no existing detectors.
When $$$n=1$$$, the answer is $$$0$$$.
First, we find a lower bound of the answer.
Suppose we install $$$k$$$ detectors. Each detector covers an interval, so its answer changes at most twice as we move from left to right: once from $$$0$$$ to $$$1$$$ and once from $$$1$$$ to $$$0$$$.
To distinguish all $$$n$$$ spots, at least one detector must return a different report for every two consecutive spots. Thus, at least $$$n-1$$$ changes are required.
Additionally, the first and last spots cannot both have all-zero reports (unless $$$n=1$$$). Therefore, at least one extra change is required at one of the endpoints.
Therefore, a lower bound on $$$k$$$ is $$$k\ge\left\lceil\frac n2\right\rceil.$$$
Next, we provide a construction using $$$k=\lceil\frac{n}{2}\rceil$$$ detectors for $$$n \ge 1$$$.
Install $$$k$$$ detectors, where detector $$$i$$$ covers $$$[i,i+k-1].$$$ All of these intervals are valid because $$$2k-1 \le n$$$.
For $$$1 \le i \le k$$$, a new interval is started for each $$$i$$$. Therefore, they are pairwise distinct.
For $$$k+1 \le i \lt 2k$$$, one interval ends for each $$$i$$$. Therefore, they are also pairwise distinct among each other. To prove that the signals for these $$$k$$$ signals are different from the first $$$k$$$ spots, we notice that the first interval includes all of the first $$$k$$$ spots, but none of these $$$k$$$.
If $$$n$$$ is even, this leaves spot $$$n$$$, which will return false for all detectors. Since this is the only spot for this, we can also distinguish hiding spot $$$n$$$.
//
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<int, int>;
void solve(void){
int n;
cin >> n;
int m;
cin >> m;
if(n==1){
cout << 0 << endl;
return;
}
vector<pair<int,int>> ans;
vector<pair<int,int>> act;
cout << (n+1)/2 << endl;
int mid = (n+1)/2;
for(int i=0; i<mid; i++){
cout << i+1 << " " << i+mid << endl;
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) solve();
return 0;
}
2261D2 - Come Be My Friend, Don't Be So Scared (Hard Version)
Author, Preparation: omsincoconut Editorial:Proof_by_QED
First, find a way to calculate some representation of all detector reports for each spot.
If two spots currently have the same detector report, they need to be distinguished by a new detector.
Suppose we represent spots with the same report as intervals. The intervals are pairwise either disjoint or one is fully encased in another. Use this to come up with a lower bound similar to the lower bound in D1.
First, we need a way to quickly calculate the set of given detectors for each hiding spot. One way to do this is with XOR hashing. Denote $$$h_i$$$ as some number representing the set of detectors that are active in hiding spot $$$i$$$. With a detector at $$$[l,r]$$$, we can XOR every number in the range from $$$l$$$ to $$$r$$$ by the same random number (this can be sped up with prefix XOR). At the end, with high probability, if $$$h_i=h_j$$$, then it means that the same set of intervals contain both positions $$$i$$$ and $$$j$$$, and if $$$h_i\ne h_j$$$, then different sets of intervals contain $$$i$$$ and $$$j$$$.
For every pair of $$$(i,j)$$$ with $$$h_i=h_j$$$, some new detector must cover exactly one of these two spots. Equivalently, exactly one of its two endpoints must lie between $$$i$$$ and $$$j$$$. If there are three indices $$$i \lt j \lt k$$$ with $$$h_i=h_j=h_k$$$, a new detector endpoint must be added between both $$$i$$$ and $$$j$$$, and $$$j$$$ and $$$k$$$. Therefore, for each index $$$i$$$, it suffices to compute the smallest $$$j$$$ with $$$h_j=h_i$$$ and $$$j \gt i$$$. Call this number $$$nxt_i$$$.
This creates $$$O(n)$$$ different intervals between $$$(i,nxt_i)$$$. The next observation is that these intervals are either nested or disjoint: they cannot intersect without one containing the other.
Suppose otherwise. Then there exist indices $$$i \lt j \lt nxt_i \lt nxt_j$$$.
Since $$$h_i=h_{nxt_i}$$$ and $$$h_j=h_{nxt_j}$$$, the sets of existing detectors covering $$$i$$$ and $$$nxt_i$$$ are identical, as are those covering $$$j$$$ and $$$nxt_j$$$.
Furthermore, $$$h_i\ne h_j$$$, since $$$nxt_i$$$ is the first occurrence of $$$h_i$$$ after $$$i$$$.
Therefore, there exists some detector that covers exactly one of $$$i$$$ and $$$j$$$.
If it covers $$$i$$$ but not $$$j$$$, it must also cover $$$nxt_i$$$, contradicting that its interval is contiguous.
Otherwise, it covers $$$j$$$ but not $$$i$$$. It must also cover $$$nxt_j$$$, but not $$$nxt_i$$$, again contradicting contiguity.
Thus, two intervals cannot partially overlap, so they must be either nested or disjoint.
If a smaller interval $$$(j,nxt_j)$$$ is completely contained inside a larger interval $$$(i,nxt_i)$$$, then the smaller interval forces a new detector endpoint inside it. This also satisfies the necessary endpoint condition for the larger interval. Therefore, we can ignore all intervals that contain another interval.
Since the original intervals are either nested or disjoint, the remaining intervals are pairwise disjoint. Let there be $$$q$$$ such intervals. Each requires at least one new detector endpoint, so at least $$$q$$$ endpoints are necessary.
We can greedily place one endpoint inside each of these intervals, for example, immediately before its right endpoint. This gives the minimum possible number of internal endpoints, $$$q$$$.
However, just placing an endpoint inside every interval is not sufficient. If both endpoints of some new detector lie between two spots with the same existing report, that detector cannot distinguish them. We need to pair the endpoints carefully, using the same construction as D1.
Suppose the selected endpoints are $$$b_1 \lt b_2 \lt \cdots \lt b_q$$$, where endpoint $$$b_i$$$ represents a change between spots $$$b_i$$$ and $$$b_i+1$$$. These divide the hiding spots into $$$q+1$$$ regions.
As in D1, we can make the new reports of all these regions pairwise distinct, except possibly the first and last regions.
If $$$q$$$ is odd, we add an endpoint before spot $$$1$$$, making the total number of endpoints even.
If $$$q$$$ is even, we can pair the $$$q$$$ endpoints directly. In this case, the first and last regions both have all new detectors inactive, while every other region has a unique report.
Therefore, if some existing report appears in both the first and last regions, we need one more detector. We do this by adding endpoints before spot $$$1$$$ and after spot $$$n$$$.
Now, let all the endpoints in increasing order be $$$c_1 \lt c_2 \lt \cdots \lt c_{2k}$$$, where $$$k$$$ is the number of new detectors. For every $$$1\le i\le k$$$, install a detector covering $$$[c_i+1,c_{i+k}]$$$.
This is exactly the construction from D1: the first $$$k$$$ endpoints start detectors one by one, and the last $$$k$$$ endpoints end them in the same order. Therefore, all regions have distinct new reports, except possibly the first and last when no extra endpoint is added.
In particular, any two spots with the same existing report lie in different regions, since at least one selected endpoint lies between every two consecutive occurrences of that report. Since these regions have different new reports (unless they are the first and last regions, which we handle separately), all spots can be distinguished.
Note that whether some existing report appears in both the first and last regions does not depend on where we choose the endpoints inside the remaining intervals. Indeed, such a report must occur at or before the left endpoint of the first remaining interval and at or after the right endpoint of the last remaining interval. Otherwise, we would obtain two intervals that partially overlap, contradicting our earlier observation.
Thus, for $$$q \gt 0$$$, the answer is
If $$$q=0$$$, all existing reports are already distinct, so the answer is $$$0$$$.
To see why this is optimal, the $$$q$$$ disjoint intervals require at least $$$q$$$ internal endpoints. If $$$q$$$ is odd, this already requires at least $$$\lceil q/2\rceil$$$ detectors.
If $$$q$$$ is even and the first and last regions contain a common report, using only $$$q/2$$$ detectors would force all their endpoints to be internal, with exactly one endpoint in each of the $$$q$$$ disjoint intervals. In particular, none of these detectors could distinguish the two occurrences of that common report, since all their endpoints would lie between those occurrences. Hence, one additional detector is necessary.
Therefore, our construction matches the lower bound and is optimal.
Finally, all intervals, the greedy endpoints, and the construction can be found in $$$O(n+m)$$$ expected time using hashing.
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define ALL(a) a.begin(),a.end()
#define RALL(a) a.rbegin(),a.rend()
#define SORT(a) sort(ALL(a))
#define RSORT(a) sort(RALL(a))
#define REV(a) reverse(ALL(a))
#define UNI(a) a.erase(unique(ALL(a)),a.end())
#define SZ(a) (int)(a.size())
#define LB(a,x) (int)(lower_bound(ALL(a),x)-a.begin())
#define UB(a,x) (int)(upper_bound(ALL(a),x)-a.begin())
#define MIN(a) *min_element(ALL(a))
#define MAX(a) *max_element(ALL(a))
using ll = long long;
using db = long double;
using i128 = __int128_t;
using u32 = uint32_t;
using u64 = uint64_t;
const int INF=INT_MAX/2;
const ll LINF=LLONG_MAX/4;
const db DINF=numeric_limits<db>::infinity();
const int MOD=998244353;
const int MOD2=1000000007;
const db EPS=1e-9;
const db PI=acos(db(-1));
template<class T>
using PQ = priority_queue<T,vector<T>,greater<T>>;
#define vv(T,a,n,...) vector<vector<T>> a(n,vector<T>(__VA_ARGS__))
#define vvv(T,a,n,m,...) vector<vector<vector<T>>> a(n,vector<vector<T>>(m,vector<T>(__VA_ARGS__)))
#define vvvv(T,a,n,m,k,...) vector<vector<vector<vector<T>>>> a(n,vector<vector<vector<T>>>(m,vector<vector<T>>(k,vector<T>(__VA_ARGS__))))
template<class T,class U>
bool chmin(T &a,U b){return b<a?a=b,1:0;}
template<class T,class U>
bool chmax(T &a,U b){return a<b?a=b,1:0;}
template<class T,class U>
T SUM(const U &a){return accumulate(ALL(a),T{});}
static inline u64 rng64(){
static u64 x=(u64)(chrono::steady_clock::now().time_since_epoch().count())*10150724397891781847ULL;
const u64 c=0xd07ebc63274654c7ull;
x+=c;
__uint128_t t=(__uint128_t)x*(x^c);
return t^(t>>64);
}
void runcase(){
int n,m;
cin >> n >> m;
vector<u64> a(n);
for(int i=0;i<m;i++){
int l,r;
cin >> l >> r;
l--;
u64 h=rng64();
a[l]^=h;
if(r<n)a[r]^=h;
}
for(int i=1;i<n;i++)a[i]^=a[i-1];
map<u64,int> last;
vector<int> dp(n),pre(n,-1);
deque<int> dq{0};
last[a[0]]=0;
int st=n,ed=-1;
for(int i=1;i<n;i++){
dp[i]=dp[dq.front()]+1;
pre[i]=dq.front();
if(last.count(a[i])){
int p=last[a[i]];
st=min(st,p);
ed=i;
while(!dq.empty()&&dq.front()<=p){
dq.pop_front();
}
}
if(!dq.empty()&&chmin(dp[i],dq.front())){
pre[i]=dq.front();
}
while(!dq.empty()&&dp[i]<dp[dq.back()]){
dq.pop_back();
}
dq.emplace_back(i);
last[a[i]]=i;
}
vector<int> pos;
for(int i=dq.front();i>0;i=pre[i]){
pos.emplace_back(i);
}
if(ed!=-1&&a[st]==a[ed]){
pos.emplace_back(st);
}
if(SZ(pos)%2==1)pos.emplace_back(n);
SORT(pos);
int h=SZ(pos)/2;
cout << h << "\n";
for(int i=0;i<h;i++){
cout << pos[i]+1 << " " << pos[i+h] << "\n";
}
}
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
int t(1);
cin >> t;
while(t--)runcase();
}
2261E - What Does the Cow Say?
Author, Preparation, Editorial: yse
Represent the string using $$$c[i]$$$, the number of consecutive opening brackets before the $$$i$$$-th closing bracket.
Consider prefix blocks and middle windows separately.
Let $$$m = \frac{n}{2}$$$ and number the closing brackets $$$1, \dots, m$$$ from left to right. Let $$$c[i]$$$ be the number of consecutive $$$\texttt{(}$$$ directly before the $$$i$$$-th $$$\texttt{)}$$$; this is $$$0$$$ if that $$$\texttt{)}$$$ follows another $$$\texttt{)}$$$.
An operation on an occurrence of $$$\texttt{()}$$$ deletes one $$$\texttt{(}$$$ and one $$$\texttt{)}$$$ from the middle of the string, then adds a $$$\texttt{(}$$$ at the very front and a $$$\texttt{)}$$$ at the very end. In terms of $$$c$$$, it removes one closing bracket, merges the run of $$$\texttt{(}$$$ before it with the run after it, and sends one $$$\texttt{(}$$$ to the far left. The final block of consecutive $$$\texttt{(}$$$ is either a prefix of the string or a window in the middle, so we handle the two cases separately.
Let's look at the first case, where the block is a prefix. Suppose the block ends at the $$$i$$$-th closing bracket.
- Perform the operation on closing brackets $$$1, 2, \dots, i-1$$$, in this order. Each operation deletes a $$$\texttt{)}$$$ and sends its $$$\texttt{(}$$$ to the front, which is still inside the prefix. After $$$i-1$$$ operations, the first $$$i$$$ closing brackets have collapsed into a single block of $$$c[1] + \dots + c[i]$$$ opening brackets.
- We have $$$k - (i-1)$$$ operations left. Each one, applied to a $$$\texttt{()}$$$ outside the prefix, sends a new $$$\texttt{(}$$$ to the front and extends the block by $$$1$$$. The block can never exceed $$$m$$$, the total number of $$$\texttt{(}$$$.
Hence, for every $$$i$$$ with $$$i - 1 \le k$$$, a prefix achieves $$$\min\bigl(m,\; c[1] + \dots + c[i] + k - (i-1)\bigr)$$$.
Now let's look at the second case, where the block is a window in the middle. Suppose the block consists of closing brackets $$$l, \dots, r$$$ with $$$l \gt 1$$$. Merging it takes $$$r - l$$$ operations, so we need $$$r - l \le k$$$. Operations outside the window only add $$$\texttt{(}$$$ at the front, which cannot help a block that is not a prefix, so all operations should be spent on the window. Each operation inside the window sends one $$$\texttt{(}$$$ out of the window, so each removed $$$\texttt{)}$$$ costs the window one $$$\texttt{(}$$$. The size of the merged block is therefore
where the $$$+1$$$ appears because the last closing bracket $$$r$$$ is not operated on.
Define $$$\text{psum}[i] = \sum_{j \le i} (c[j] - 1)$$$ with $$$\text{psum}[0] = 0$$$. The best window ending at $$$r$$$ has value
where $$$p = l - 1$$$. Since $$$c[j] - 1$$$ can be negative, the best window is not always as long as allowed, and this is handled correctly by taking the minimum over the whole range of allowed $$$p$$$. A sliding-window minimum (monotonic deque) computes it in $$$\mathcal{O}(n)$$$ total.
#include <bits/stdc++.h>
using namespace std;
#define int long long
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int m = n / 2;
vector<int> c;
c.push_back(0);
int run = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '(') run++;
else {
c.push_back(run);
run = 0;
}
}
int mx = 0, cur = 0;
for(int i = 1; i <= m; i++) {
cur += c[i];
if(i - 1 <= k) mx = max(mx, min(m, cur + k - (i - 1)));
}
vector<int> a(m + 1), pre(m + 1);
for(int i = 1; i <= m; i++) {
a[i] = c[i] - 1;
pre[i] = pre[i - 1] + a[i];
}
deque<int> dq;
for(int y = 1; y <= m; y++) {
int x = y - 1;
while(!dq.empty() && pre[dq.back()] >= pre[x]) dq.pop_back();
dq.push_back(x);
while(!dq.empty() && dq.front() < y - (k + 1)) dq.pop_front();
mx = max(mx, min(m, pre[y] - pre[dq.front()] + 1));
}
cout << mx << "\n";
}
signed main() {
int t;
cin >> t;
while(t--) solve();
}
2261F1 - Plegma II: Ask Me Any Cell (Easy Version)
Author, Preparation, Editorial: SpyrosAliv
Solve in 1D: the grid is one row and $$$n$$$ columns, and $$$k = n$$$.
Extend your 1D solution to 2D.
Note that Circuity must take one of four actions. It would be great if we would use $$$S$$$ to always send a $$$2$$$ bit integer, regardless of how big the subgrid is.
First, let's see how to solve the $$$1$$$-dimensional version: if we only have a single row. We must send a $$$1$$$ bit integer (delete left or right). The best way to do this is using parity. For example, if the parity is odd, then do action $$$\texttt{L}$$$, if the parity is even do action $$$\texttt{R}$$$. Then, the construction would be quite simple:
If the target cell is not cell $$$1$$$, then place all $$$0$$$s, except for the cell to the left of the target cell. For example, if the target cell is cell $$$4$$$, we would use the grid $$$\texttt{001000...}$$$. The idea is that when a $$$1$$$ is removed, the parity changes, so our direction does too.
Obviously, if the target cell is cell $$$1$$$, send a row full of $0$s.
Here, we would use $$$A = \texttt{RLRL...}$$$ (though we only ever use indices $$$0$$$ and $$$1$$$).
Extend to full grid:
We use two phases. In the first phase, we locate the target's row. In the second phase, we implement the 1D solution and we are done.
Note that the 1D solution only uses at most one $$$1$$$. So the next idea is to use a lot of $1$s to identify whether we are in the first phase or the second phase of the solution. Specifically:
- If there are $$$S = 0$$$ or $$$S = 1$$$, we are in phase $$$2$$$ of solution (1D),
- If $$$S \gt 1$$$, we are in phase $$$1$$$ of solution ($$$2D$$$) and need to remove either $$$\texttt{U}$$$ or $$$\texttt{D}$$$.
For phase 1, we will again use parity in the exact same way as the 1D solution. Note that a row full of $$$1$$$s has an even amount of $$$1$$$s and does not affect parity. If $$$S$$$ is odd, we remove the up row, otherwise the down row. To do this, first we fix the target row as we would fix it in the 1D version. Then, depending on whether we had to use one $$$1$$$ or no $1$s, we can place two $0$s appropriately on the row below and on the row above.
For example, if the target cell is $$$(2, 2)$$$, we would use something like:
$$$\texttt{1111111...}$$$ (even sum)
$$$\texttt{1000000...}$$$ (odd sum)
$$$\texttt{0111111...}$$$ (odd sum)
$$$\texttt{1111111...}$$$ (even sum)
$$$\texttt{...}$$$ (even sum)
Since the sum is even, we keep removing from below until we remove row $$$3$$$. The parity flips, so now we remove from the top. Then we are left with a single row with only one $$$1$$$ and so we use the 1D solution.
Another example, if the target cell is $$$(2, 1)$$$:
$$$\texttt{01111...}$$$ (odd sum)
$$$\texttt{00000...}$$$ (even sum)
$$$\texttt{11111...}$$$ (even sum)
$$$\texttt{...}$$$ (even sum)
If the target is cell $$$(1, 2)$$$:
$$$\texttt{10000...}$$$
$$$\texttt{01111...}$$$
$$$\texttt{11111...}$$$
$$$\texttt{...}$$$
If it is cell $$$(1, 1)$$$:
$$$\texttt{00000...}$$$
$$$\texttt{11111...}$$$
$$$\texttt{11111...}$$$
$$$\texttt{...}$$$
And so on. Note that the only special cases are when $$$r = 1$$$ or $$$r = n$$$, which are very easy to take care of. This solution uses at most $$$N+1$$$ zeros.
Also, $$$A$$$ looks something like $$$\texttt{RLDUDUDUDU...}$$$, so implementation should be quite simple.
#include <bits/stdc++.h>
using namespace std;
void solve_ez() {
cout << "001\n101\n111\n\n";
cout << "100\n110\n011\n\n";
cout << "111\n010\n010\n\n";
cout << "111\n111\n110\n\n";
cout << "111\n100\n010\n\n";
cout << "111\n011\n000\n\n";
cout << "000\n110\n000\n\n";
cout << "111\n111\n111\n\n";
cout << "110\n111\n011\n\n";
cout << "RDUDLLRURU\n";
}
void encode(int n, int r, int c) {
vector<vector<int>> g(n+1, vector<int>(n+1, 1));
for (int i = 1; i <= n; i++) g[r][i] = 0;
if (c > 1) {
g[r][c-1] = 1;
if (r < n) g[r+1][1] = 0;
}
else {
if (r > 1) g[r-1][1] = 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << g[i][j];
}
cout << "\n";
}
cout << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
if (n == 3) {
solve_ez();
return 0;
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n; c++) {
encode(n, r, c);
}
}
cout << "RL";
for (int s = 2; s <= n*n; s++) {
if (s & 1) cout << "U";
else cout << "D";
}
cout << "\n";
}
2261F2 - Plegma II: Ask Me Any Cell (Hard Version)
Author, Preparation, Editorial: SpyrosAliv
The answer is $$$f(n) = 3$$$ for every $$$n \ge 3$$$.
Circuity only sees $$$S = hw - z$$$, where $$$h \times w$$$ is the current rectangle and $$$z$$$ the number of zeros in it. The rectangle shrinks in a predictable way, so the number of zeros is the only thing you really control: think of it as a mode that you can switch down at any time by putting a zero into the strip that is about to be deleted.
Let us first understand what Circuity actually sees. At any moment it looks at some $$$h \times w$$$ rectangle; if this rectangle contains $$$z$$$ zeros, it senses $$$S = hw - z$$$ and performs $$$A_S$$$. The pair $$$(h, w)$$$ changes in a completely predictable way along any route, so the only thing Verity really controls is $$$z$$$. Zeros never appear, and a zero disappears exactly when the strip containing it is deleted. This suggests flipping the point of view: instead of designing grids, we design a route (which strips are deleted and in which order) together with a schedule telling how many zeros should be present before each move. Any non-increasing schedule can be realised. Whenever the count has to drop, we put the extra zeros into the strip that the current move deletes (deleted strips are disjoint, so there is always room), and if one zero is supposed to survive until the end, we put it into the target cell. So the number of zeros is a "mode" that we can switch down whenever we like, and the decoder reads the mode through $$$S$$$. From now on we only talk about routes and schedules. We write $$$\texttt{U}, \texttt{D}, \texttt{L}, \texttt{R}$$$ for deleting the top row, bottom row, left column and right column, and we will use repeatedly that a corner of the grid stays the same corner of every rectangle that contains it; for example, an execution whose target is a top corner can never perform $$$\texttt{U}$$$.
The answer is $$$f(n) = 3$$$ for all $$$n \ge 3$$$. We first show how to do it with three zeros and then why two are not enough.
Upper bound: three zeros suffice.
The natural plan is to fix the rows first and the columns afterwards. While the rectangle is $$$h \times n$$$, three zeros give $$$S = nh - 3$$$ and two zeros give $$$S = nh - 2$$$; these values are different for different $$$h$$$, so we can simply declare that three zeros mean $$$\texttt{U}$$$ and two zeros mean $$$\texttt{D}$$$, and Verity can move the top or the bottom border as he likes by choosing when to drop the third zero.
The column stage is where one has to be a bit careful. In an $$$h \times w$$$ rectangle with $$$z$$$ zeros we sense $$$hw - z$$$, and we again want two modes, one for $$$\texttt{L}$$$ and one for $$$\texttt{R}$$$, whose values never coincide for different widths. If we shrank all the way down to one row this would fail: $$$1 \times w$$$ with two zeros and $$$1 \times (w - 1)$$$ with one zero both give $$$S = w - 2$$$. With three rows there is no such problem, because $$$3w - 3$$$, $$$3w - 2$$$ and $$$3w - 1$$$ have different remainders modulo $$$3$$$, so three different modes fit without any conflict. This is why we stop the vertical stage at three rows, and it remains to understand what a $$$3 \times 1$$$ column can do with the small values $$$S \in {0, 1, 2}$$$.
If the column contains two zeros, it senses $$$1$$$. We set $$$A_1 = \texttt{U}$$$; the remaining $$$2 \times 1$$$ column contains two zeros ($$$S = 0$$$) or one ($$$S = 1$$$), and with $$$A_0 = A_1 = \texttt{U}$$$ the bottom cell survives either way. If the column contains one zero, it senses $$$2$$$. We set $$$A_2 = \texttt{D}$$$; the remaining $$$2 \times 1$$$ column contains one zero ($$$S = 1$$$, move $$$\texttt{U}$$$, the middle cell survives) or none ($$$S = 2$$$, move $$$\texttt{D}$$$, the top cell survives). So entering the final column with two zeros means "bottom cell", and entering it with one zero lets us choose between the top and the middle cell. To enter with two zeros, the column stage must perform $$$\texttt{R}$$$ first with three zeros and $$$\texttt{L}$$$ afterwards with two; to enter with one zero, it performs $$$\texttt{L}$$$ first with two zeros and $$$\texttt{R}$$$ afterwards with one. Altogether the decoder is
$$$A_0 = A_1 = \texttt{U}$$$, $$$A_2 = \texttt{D}$$$; $$$A_{3w-3} = \texttt{R}$$$, $$$A_{3w-2} = \texttt{L}$$$, $$$A_{3w-1} = \texttt{R}$$$ for $$$2 \le w \le n$$$; $$$A_{nh-3} = \texttt{U}$$$, $$$A_{nh-2} = \texttt{D}$$$ for $$$4 \le h \le n$$$,
and everything else is arbitrary. The three groups use $$$S \in {0, 1, 2}$$$, $$$3 \le S \le 3n - 1$$$ and $$$S \ge 4n - 3$$$, and $$$4n - 3 \gt 3n - 1$$$ for $$$n \ge 3$$$, so nothing overlaps.
Now the encoding of a target $$$(r, c)$$$ just follows this plan. Let $$$a = \min(r - 1, n - 3)$$$ and $$$p = r - a$$$. We first perform $$$\texttt{U}$$$ $$$a$$$ times with three zeros and then $$$\texttt{D}$$$ $$$n - 3 - a$$$ times with two zeros, which leaves exactly the rows $$$a + 1, a + 2, a + 3$$$, and the target is the $$$p$$$-th of them; by the choice of $$$a$$$ we have $$$p \in {1, 2, 3}$$$, and $$$p = 3$$$ happens only for $$$r = n$$$. If $$$p \le 2$$$ we perform $$$\texttt{L}$$$ $$$c - 1$$$ times with two zeros, then $$$\texttt{R}$$$ $$$n - c$$$ times with one zero, and we are in a $$$3 \times 1$$$ column with one zero: we perform $$$\texttt{D}$$$, dropping the zero if $$$p = 1$$$ and keeping it if $$$p = 2$$$, and the last move finishes in the right cell as explained above. If $$$p = 3$$$ we perform $$$\texttt{R}$$$ $$$n - c$$$ times with three zeros, then $$$\texttt{L}$$$ $$$c - 1$$$ times with two zeros, and the column with two zeros ends in the bottom cell by itself. For $$$n = 3$$$ the vertical stage is empty and everything else is identical. Every schedule starts with at most three zeros, so $$$f(n) \le 3$$$.
Lower bound: two zeros are not enough.
With at most two zeros there are only three modes, and the trouble comes from the very end of the execution: the last few moves of every target sense tiny values of $$$S$$$, and the same $$$A_1, A_2, \dots$$$ have to serve targets lying in different directions. We make this precise by proving a statement that is much stronger than what we need: for any $$$n \ge 2$$$ and any decoder, it is impossible to encode all four corners of the grid with at most two zeros each. We call the four executions TL, TR, BL, BR after their target corners, and we say that an execution is $$$2$$$-dimensional while its rectangle has $$$h, w \ge 2$$$.
Disclaimer: It should be intuitive that $$$2$$$ is insufficient due to the corners, but here's the whole proof for fun. Definitely written by me without any help from any entities whatsoever...
Assume that all four corners are reachable. Rotating the whole picture if necessary, we may assume $$$A_2 = \texttt{U}$$$. The strategy is to look at the executions near their end, where the sensed values are small, and to pin down $$$A_1, \dots, A_8$$$ one after another until the bottom-right corner becomes impossible.
Consider TL (the same reasoning works for TR). It can never sense $$$S = 2$$$, because $$$\texttt{U}$$$ would kill its target. Before its last move the rectangle has two cells, so there $$$S \le 2$$$ and hence $$$S \le 1$$$. Take the first moment at which $$$S \le 1$$$. The previous value was neither $$$2$$$ nor at most $$$1$$$, so it was at least $$$3$$$, which means that the move in between removed at least two ones. Such a move is only possible from a $$$2$$$-dimensional rectangle, and the new rectangle contains at most two zeros and at most one $$$1$$$, so at most three cells. Going through the sizes, either a $$$2 \times 2$$$ with one zero ($$$S = 3$$$) became a two-cell rectangle keeping its zero, or a $$$3 \times 2$$$ or $$$2 \times 3$$$ with two zeros ($$$S = 4$$$) became a three-cell rectangle keeping both zeros; in both cases the new value is exactly $$$S = 1$$$. So both TL and TR execute $$$A_1$$$ inside a $$$1$$$-dimensional rectangle. The only action that kills neither top corner is $$$\texttt{D}$$$, hence $$$A_1 = \texttt{D}$$$, and since $$$\texttt{D}$$$ must be legal there, that rectangle is a column. Therefore the move into it deleted a column of a $$$2 \times 2$$$ (sensing $$$3$$$) or of a $$$3 \times 2$$$ (sensing $$$4$$$); for TL this move is $$$\texttt{R}$$$ and for TR it is $$$\texttt{L}$$$, so $$${A_3, A_4} = {\texttt{L}, \texttt{R}}$$$. Reflecting left and right if necessary, $$$A_3 = \texttt{L}$$$ and $$$A_4 = \texttt{R}$$$. But now TL cannot use the $$$2 \times 2$$$ option, since $$$A_3 = \texttt{L}$$$ kills it, and we obtain the key fact $$$(\ast)$$$: TL starts with two zeros, keeps both of them until it reaches a $$$3 \times 2$$$ rectangle, and then plays $$$A_4 = \texttt{R}$$$. For $$$n = 2$$$ this is already impossible, so from now on $$$n \ge 3$$$.
Before going on, let us record what the four known actions imply for executions with few zeros. First, consider an execution with no zeros at all that starts from a $$$2$$$-dimensional rectangle. In a zero-free row or column of length at least $$$3$$$ it would sense both $$$3$$$ and $$$2$$$, but $$$A_3 = \texttt{L}$$$ and $$$A_2 = \texttt{U}$$$ cannot both be legal in the same row or column. So the execution first becomes $$$1$$$-dimensional as a two-cell rectangle, which must be a column because $$$A_2 = \texttt{U}$$$, and its bottom cell survives; the rectangle just before that is an all-ones $$$2 \times 2$$$ in which $$$A_4 = \texttt{R}$$$ keeps the left column. We get fact (A): a zero-free execution from a $$$2$$$-dimensional rectangle can only end in the bottom-left corner of that rectangle, and it passes through an all-ones $$$2 \times 2$$$.
Next, executions with at most one zero. A row of length at least $$$2$$$ fails, because it eventually senses $$$1$$$ or $$$2$$$ and both $$$\texttt{D}$$$ and $$$\texttt{U}$$$ are illegal in a row. A column of height at least $$$4$$$ fails, because it senses $$$3$$$ at some point and $$$\texttt{L}$$$ is illegal in a column. A column of height $$$3$$$ cannot end in its top cell: with one zero it senses $$$2$$$ and plays $$$\texttt{U}$$$, with no zero it senses $$$3$$$. Finally, by (A), an execution with one zero whose target is a right corner cannot afford to lose its zero while it is still $$$2$$$-dimensional. Put together, this is fact (B), and it has two consequences we will use: a one-zero execution to TR must reach a $$$2 \times 2$$$ with one zero and then play $$$\texttt{L}$$$, and a one-zero execution to BR enters its final column at height $$$2$$$ or $$$3$$$. One more small fact (C): if a one-zero execution aiming at a right corner is in a $$$2 \times w$$$ rectangle, then $$$A_{2j-1} = \texttt{L}$$$ for every $$$2 \le j \le w$$$, because it cannot delete a row (that would leave a row of length at least $$$2$$$), it cannot play $$$\texttt{R}$$$, and it keeps its zero, so in each $$$2 \times j$$$ it senses $$$2j - 1$$$ and has to play $$$\texttt{L}$$$.
Now we can determine how many zeros each corner uses. Two opposite corners cannot start with the same number of zeros, because they would sense the same $$$S$$$ at the start and the common first move would kill one of them. More generally, two executions that are in the same state (same rectangle, same number of zeros) make the same move, so two executions can only diverge at a move where one of them loses a zero. By $$$(\ast)$$$ TL uses two zeros, so BR does not, and BR cannot use zero zeros by (A); hence BR uses exactly one zero. If TR also used one zero, then TR and BR would both keep their zero while $$$2$$$-dimensional, so they would make identical moves, which can only be $$$\texttt{L}$$$; they would enter a column of height $$$n \ge 3$$$ with at most one zero, and by (B) TR cannot survive that. Hence TR uses exactly two zeros, and consequently its opposite corner BL uses at most one. Finally, TL and TR both start with two zeros and move identically (only $$$\texttt{D}$$$ is allowed, so the width stays $$$n \ge 3$$$) until one of them loses a zero; by $$$(\ast)$$$ it is not TL, and TR cannot lose both zeros by (A). So right after that move we have a successful one-zero TR execution starting from an $$$h \times n$$$ rectangle, and $$$h \ge 3$$$ because TL still has to reach a $$$3 \times 2$$$.
This one-zero TR execution determines $$$A_5$$$. By (B) it cannot enter a column while its height is at least $$$3$$$, so at some point it goes from height $$$3$$$ to height $$$2$$$ at some width $$$w \ge 2$$$. If $$$w = 2$$$ this is a $$$3 \times 2$$$ with one zero, $$$S = 5$$$, and the move is $$$\texttt{D}$$$; if $$$w \ge 3$$$ it then lives in a $$$2 \times w$$$ strip and (C) gives $$$A_5 = \texttt{L}$$$. So $$$A_5 \in {\texttt{D}, \texttt{L}}$$$. On the other hand BR, which has one zero, either goes from height $$$3$$$ to $$$2$$$ while $$$2$$$-dimensional, which at width $$$2$$$ needs $$$A_5 = \texttt{U}$$$ and at width at least $$$3$$$ gives $$$A_5 = \texttt{L}$$$ by (C), or it enters its final column at height $$$3$$$, i.e. from a $$$3 \times 2$$$ with one zero, which needs $$$A_5 = \texttt{L}$$$. So $$$A_5 \in {\texttt{U}, \texttt{L}}$$$, and together $$$A_5 = \texttt{L}$$$.
The next value to look at is $$$A_6$$$, and we claim $$$A_6 \in {\texttt{U}, \texttt{R}}$$$. Suppose not. By (A), a zero-free execution starting from a $$$2$$$-dimensional rectangle of width at least $$$3$$$ has to enter its all-ones $$$2 \times 2$$$ from an all-ones $$$3 \times 2$$$ by $$$\texttt{U}$$$ or from an all-ones $$$2 \times 3$$$ by $$$\texttt{R}$$$, both with $$$S = 6$$$, which is now impossible; a zero-free row of length at least $$$3$$$ fails as well. So under our assumption no zero-free execution from a rectangle of width at least $$$3$$$ can succeed. Then BL must use exactly one zero, and BL and BR move identically (only $$$\texttt{U}$$$, so the width stays $$$n \ge 3$$$) until one of them loses its zero, which has to happen while they are $$$2$$$-dimensional since a $$$1 \times n$$$ row fails. But the execution that loses its zero becomes a zero-free execution of width $$$n \ge 3$$$, which we have just excluded. This contradiction proves $$$A_6 \in {\texttt{U}, \texttt{R}}$$$.
From here $$$A_7$$$ and $$$A_8$$$ follow quickly. By $$$(\ast)$$$, TL reaches a $$$3 \times 2$$$ with two zeros, and the rectangle before it is either a $$$4 \times 2$$$, sensing $$$6$$$ and needing $$$\texttt{D}$$$, which we just excluded, or a $$$3 \times 3$$$, sensing $$$7$$$ and needing $$$\texttt{R}$$$. So $$$A_7 = \texttt{R}$$$. Going back to the one-zero TR execution and the width $$$w$$$ at which it goes from height $$$3$$$ to $$$2$$$: $$$w = 2$$$ would need $$$A_5 = \texttt{D}$$$, but $$$A_5 = \texttt{L}$$$, and $$$w \ge 4$$$ would need $$$A_7 = \texttt{L}$$$ by (C), but $$$A_7 = \texttt{R}$$$. So $$$w = 3$$$, the rectangle is a $$$3 \times 3$$$ with one zero, it senses $$$8$$$, and the move is $$$\texttt{D}$$$. So $$$A_8 = \texttt{D}$$$.
Now BR has nowhere to go. It has exactly one zero, and every move decreases $$$h + w$$$ by one, from $$$2n \ge 6$$$ down to $$$2$$$, so at some moment $$$h + w = 6$$$. By (B) this rectangle is not a $$$1 \times 5$$$ or $$$5 \times 1$$$, so it is a $$$2 \times 4$$$, a $$$3 \times 3$$$ or a $$$4 \times 2$$$, and it still contains the zero. It therefore senses $$$7$$$, $$$8$$$ or $$$7$$$ and performs $$$A_7 = \texttt{R}$$$, $$$A_8 = \texttt{D}$$$ or $$$A_7 = \texttt{R}$$$, each of which kills the bottom-right corner. This contradiction finishes the proof.
So with two zeros some corner is always unreachable, which gives $$$f(n) \ge 3$$$, and together with the construction $$$f(n) = 3$$$. The solution runs in $$$O(n^3)$$$, which is just the size of the output.
#include <bits/stdc++.h>
using namespace std;
int n;
string mv;
vector<int> zc;
void add(char ch, int cnt, int z) {
for (int i = 0; i < cnt; i++) {
mv += ch;
zc.push_back(z);
}
}
int route(int r, int c) {
mv = "";
zc.clear();
int up = min(r - 1, n - 3);
add('U', up, 3);
add('D', n - 3 - up, 2);
int p = r - up;
if (p == 3) {
add('R', n - c, 3);
add('L', c - 1, 2);
add('U', 2, 2);
return 1;
}
add('L', c - 1, 2);
add('R', n - c, 1);
add('D', 1, 1);
if (p == 1) {
add('D', 1, 0);
return 0;
}
add('U', 1, 1);
return 1;
}
int main() {
cin >> n;
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n; c++) {
int last = route(r, c);
vector<string> g(n, string(n, '1'));
int x1 = 0, x2 = n - 1, y1 = 0, y2 = n - 1;
for (int i = 0; i < (int)mv.size(); i++) {
int nxt = i + 1 < (int)mv.size() ? zc[i + 1] : last;
int k = zc[i] - nxt;
if (mv[i] == 'U') {
for (int j = 0; j < k; j++) g[x1][y1 + j] = '0';
x1++;
} else if (mv[i] == 'D') {
for (int j = 0; j < k; j++) g[x2][y1 + j] = '0';
x2--;
} else if (mv[i] == 'L') {
for (int j = 0; j < k; j++) g[x1 + j][y1] = '0';
y1++;
} else {
for (int j = 0; j < k; j++) g[x1 + j][y2] = '0';
y2--;
}
}
if (last) g[r - 1][c - 1] = '0';
for (int i = 0; i < n; i++) cout << g[i] << '\n';
}
}
string a(n * n + 1, 'U');
a[2] = 'D';
for (int w = 2; w <= n; w++) {
a[3 * w - 3] = 'R';
a[3 * w - 2] = 'L';
a[3 * w - 1] = 'R';
}
for (int h = 4; h <= n; h++) {
a[n * h - 3] = 'U';
a[n * h - 2] = 'D';
}
cout << a << '\n';
}
2261G - 1 2 3 and XOR, Where Did Everybody Go?
Author, Preparation, Editorial: chromate00
You do not need to know the entire array $$$a$$$ to find $$$f(a)$$$. In fact, you can compute $$$f(a)$$$ by only knowing the XOR and AND over elements $$$a$$$.
Finding how many values XOR $$$x$$$ lie in $$$[l,r]$$$ is a simple trie problem. Solving this over a prefix is also simple due to offline processing or persistence.
Prefix ANDs of an array contain very few values, and they can be maintained efficiently even if we add values in the front.
Let's first consider how $$$f(a)$$$ for a static array $$$a$$$ is calculated.
For some $$$0 \le b \lt 25$$$, let's assume the $$$b$$$-th binary digit of the XOR is $$$1$$$, but the same binary digit of some element is $$$0$$$. Then, we can increment that element until that digit becomes $$$1$$$, and then the $$$b$$$ lowest bits of the new values would be $$$0$$$ so we can change all lower digits of the XOR to $$$0$$$ as well. Therefore, assuming the XOR of the array was $$$X$$$ and the AND of the array was $$$A$$$, the following pseudocode accurately calculates $$$f(a)$$$:
X = xor(a)
A = and(a)
for bit from 24 to 0:
if((X&(1<<bit)) and !(A&(1<<bit))):
break
ans+=X&(1<<bit)
return ans
We denote the value returned by the pseudocode as $$$g(X,A)$$$. Let $$$P_i = a_1 \oplus \ldots \oplus a_i$$$ (with $$$P_0 = 0$$$), so the subarray $$$[l, r]$$$ has XOR $$$P_r \oplus P_{l-1}$$$, and $$$A(l, r)$$$ denotes its AND. We want to sweep $$$r$$$ from $$$1$$$ to $$$n$$$ and compute $$$\sum_{l \le r} g(P_r \oplus P_{l-1}, A(l, r))$$$ for each $$$r$$$.
We fix $$$r$$$ first. As $$$l$$$ decreases, $$$A(l,r)$$$ can only lose bits, so there are at most $$$\log A + 1$$$ distinct values of $$$A(l,r)$$$. We call the blocks of contiguous $$$l$$$ whose $$$A(l,r)$$$ are identical a batch. $$$A$$$ is fixed in a batch, so we need $$$\sum_{q \in Q} g(P_r \oplus q, A)$$$ where $$$Q$$$ is the multiset of $$$P_{l-1}$$$ over all $$$l$$$ in the batch.
For each batch, insert every $$$q \in Q$$$ into a binary trie from the highest bit down, but walk it differently depending on $$$A$$$:
- at a bit where $$$A$$$ has a $$$1$$$, every $$$q$$$ goes to the same child, and that child records how many inserted $$$q$$$ have a $$$1$$$ at this bit;
- at a bit where $$$A$$$ has a $$$0$$$, $$$q$$$ goes to the child given by its own bit, as in an ordinary trie.
To evaluate the sum, walk down with $$$P_r$$$. At a bit $$$b$$$ where $$$A$$$ has a $$$1$$$, the bit of $$$X = P_r \oplus q$$$ is $$$1$$$ exactly when $$$q$$$'s bit differs from $$$P_r$$$'s, so we add $$$2^b$$$ times the number of such $$$q$$$ below the current node, which the recorded count gives directly. At a bit where $$$A$$$ has a $$$0$$$, every $$$q$$$ whose bit differs from $$$P_r$$$'s makes $$$X$$$'s bit $$$1$$$ and stops contributing, so we only continue into the child matching $$$P_r$$$'s bit (and stop if it does not exist). This is a single root-to-leaf path, so each batch is answered in $$$O(\log A)$$$.
When the right endpoint moves from $$$r$$$ to $$$r+1$$$, we maintain the batches as follows.
- every batch's AND becomes $$$A$$$ AND $$$a_{r+1}$$$; a batch whose AND changed is rebuilt, because its trie depends on $$$A$$$;
- adjacent batches that now have equal ANDs are merged, inserting the values of the smaller one into the trie of the larger one;
- a new batch $$${r + 1}$$$ with AND $$$a_{r+1}$$$ and $$$Q = {P_r}$$$ is added (or $$$P_r$$$ joins the last batch if its AND equals $$$a_{r+1}$$$).
The AND of a fixed left endpoint loses a bit every time it changes, so each value is rebuilt at most $$$\log A$$$ times, for $$$O(n \log^2 A)$$$ in total. By small-to-large, each value is moved at most $$$\log n$$$ times, for $$$O(n \log n \log A)$$$. Each step queries $$$O(\log A)$$$ batches in $$$O(\log A)$$$ each. This is $$$O(n \log A (\log n + \log A))$$$ time and $$$O(n \log A)$$$ memory.
#include <bits/stdc++.h>
using i64 = long long;
constexpr int B = 25;
int cnt[1 << B];
void solve() {
int n;
std::cin >> n;
std::vector<int> a(n);
for (int i = 0; i < n; i++) std::cin >> a[i];
i64 ans = 0;
std::vector next(n + 1, std::array<int, B>());
std::vector ord(n, std::array<char, B>());
next[n].fill(n);
for (int i = n - 1; i >= 0; i--) {
next[i] = next[i + 1];
for (int b = 0; b < B; b++) if (~a[i] >> b & 1) next[i][b] = i;
std::iota(ord[i].begin(), ord[i].end(), 0);
std::sort(ord[i].begin(), ord[i].end(), [&](char x, char y) { return next[i][x] < next[i][y]; });
}
std::vector<std::vector<std::pair<int, int>>> occ(n + 1);
for (int b = 0; b < B; b++) {
int c = 0;
for (int i = n - 1; i >= 0; i--) {
c ^= a[i];
if (a[i] >> b & 1) {
int v = 0;
for (int j = b; j < B; j++) if (next[i][j] != i) v |= 1 << j;
for (int j = 0; j < B; ) {
int k = j;
bool f = false;
while (k < B && next[i][ord[i][j]] == next[i][ord[i][k]]) {
if (ord[i][k] >= b) f = true;
k++;
}
if (!f) {
j = k;
continue;
}
if (next[i][ord[i][j]] != i) {
occ[i].emplace_back((c ^ v) >> b, 1);
occ[next[i][ord[i][j]]].emplace_back((c ^ v) >> b, -1);
}
while (j < k) {
if (v >> ord[i][j] & 1) v ^= 1 << ord[i][j];
j++;
}
if (~v >> b & 1) break;
}
}
}
c = 0;
for (int i = n - 1; i >= 0; i--) {
cnt[c >> b]++;
c ^= a[i];
for (auto [x, m] : occ[i]) {
ans += 1LL * cnt[x] * m * (1 << b);
}
}
c = 0;
for (int i = n - 1; i >= 0; i--) {
cnt[c >> b] = 0;
c ^= a[i];
}
for (int i = 0; i <= n; i++) occ[i].clear();
}
std::cout << ans << "\n";
}
int main() {
std::ios::sync_with_stdio(0);
std::cin.tie(0);
int t;
std::cin >> t;
while (t--) solve();
}
2261H - Oh Tree Tree Tree, No Need to Leave
Author & Editorial: SpyrosAliv
Preparation: SpyrosAliv & ttamx
The solution is extremely simple.
Read up on hamming codes if you do not know them.
It is actually possible to restore the correct order of the bits, regardless of how many nodes are flipped. This can be done in the following strategy:
Isabel will place the string on the tree using a DFS. Starting from node $$$1$$$, whenever she places a $$$0$$$ she recurses to the left child, and whenever she places a $$$1$$$ she recurses to the right child. The exception is of course at a leaf node, in which case she always backtracks.
Tara will do the exact same, this time in order to retrieve the string (possibly with a flip at a single bit). Specifically, when she sees a $$$0$$$ she goes left and when he sees a $$$1$$$ she goes right.
Using this strategy, Tara receives the original string with at most one flip. This is a classic problem that can be solved using hamming codes.
#ifdef LOCAL
#include <bits/include_all.h>
#else
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#endif
#pragma GCC target ("avx2")
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define int long long
using namespace std;
using namespace __gnu_pbds;
template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T> inline bool umin(T &a, const T &b) { if(a > b) { a = b; return 1; } return 0; }
template <typename T> inline bool umax(T &a, const T &b) { if(a < b) { a = b; return 1; } return 0; }
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
const ll mod = 998244353;
const ll inf = 1e18;
const int MAX = 2e5 + 42;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<ll> dis(1, inf);
void solve_first() {
int n, h;
cin >> n >> h; int m = (1 << h) - 1;
string s;
cin >> s;
s = "0" + s;
string ans(m + 1, '0');
for(int i = 1; i <= m; i++) {
if(i & i - 1) {
int idx = i - __lg(i) - 1;
if(idx > n) continue;
ans[i] = s[idx];
for(int j = 0; j < h; j++) {
if(i >> j & 1) ans[1 << j] ^= s[idx] & 1;
}
}
}
string res(m + 1, '0');
int idx = 1;
function<void(int)> dfs = [&](int v) {
char cr = ans[idx++];
res[v] = cr;
vector<int> c;
if(2 * v + 1 <= m) {
c.push_back(2 * v);
c.push_back(2 * v + 1);
if(cr & 1) swap(c[0], c[1]);
}
for(auto to : c) dfs(to);
};
dfs(1);
res.erase(res.begin());
cout << res << '\n';
}
void solve_second() {
int n, h;
cin >> n >> h; int m = (1 << h) - 1;
string s;
cin >> s;
s = "0" + s;
string res = "0";
int idx = 1;
function<void(int)> dfs = [&](int v) {
char cr = s[v];
res.push_back(cr);
vector<int> c;
if(2 * v + 1 <= m) {
c.push_back(2 * v);
c.push_back(2 * v + 1);
if(cr & 1) swap(c[0], c[1]);
}
for(auto to : c) dfs(to);
};
dfs(1);
int bad = 0;
for(int i = 1; i <= m; i++) {
if(res[i] & 1) bad ^= i;
}
res[bad] ^= 1;
string ans(n, '0');
for(int i = 1; i <= m; i++) {
if(i & i - 1) {
int idx = i - __lg(i) - 1;
if(idx > n) continue;
ans[idx - 1] = res[i];
}
}
cout << ans << '\n';
}
string who;
void solve() {
if(who == "first") solve_first();
else solve_second();
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> who;
int ttt = 1;
cin >> ttt;
while(ttt--) {
solve();
}
}








In Problem D1 idk why i was trying to find the most optimal answer so bad that even though i got the solution, i was thinking that my solution is wrong and there must be a smaller number of sensor possible.
Turtle speed editorial :O
I solved E like this, im trying to merge some run with some another run (of left brackets from left to right.) I keep a prefix sum of gain in longest length if i merge some runs (length of left run + length of right run — number of right brackets in between), then I use sparsetable to query the best answer for each run of left brackets building leftwards and I handle the first run of brackets differently since you dont lose a left bracket from an operation
I solved G without trie or any data structures: 395029892