Let's focus on the number of occurrences of each element: let $$$c_i$$$ be the number of time that element $$$i$$$ occurs in the array. To keep a subsequence is to decrease each $$$c_i$$$ by a non-negative integer. We need to make all the non-zero elements in $$$c$$$ the same while maximizing the sum of $$$c$$$.
For each integer $$$x$$$: suppose the value of all non-zero elements in $$$c$$$ is $$$x$$$, what is the length of the longest subsequence?
For those $$$c_i \lt x$$$, we decrease it to $$$0$$$; for those $$$c_i\ge x$$$, we decrease it to $$$x$$$.
By Caylex.
def solve():
n = int(input())
ls = list(map(int, input().split()))
a = [0] * n
for x in ls:
a[x - 1] += 1
a = sorted(a)
s = sum(a)
ans = s
for i in range(n):
ans = min(ans, s - (n - i) * a[i])
print(n - ans)
return
t = int(input())
for _ in range(t):
solve()
How to check if there is at least one way to choose the sets?
Obviously, we should choose all the sets.
How to greedily find two more solutions to choose the sets?
We should choose all the sets but one.
By Caylex.
def solve():
n, m = map(int, input().split())
cnt = [0] * m
t = 0
v = []
for i in range(n):
v.append([])
inp = list(map(int, input().split()))
l = inp[0]
for j in range(1, l + 1):
x = inp[j]
x -= 1
t += not cnt[x]
cnt[x] += 1
v[i].append(x)
ans = t == m
for i in range(n):
for x in v[i]:
cnt[x] -= 1
t -= not cnt[x]
ans += t == m
for x in v[i]:
t += not cnt[x]
cnt[x] += 1
print("YES" if ans >= 3 else "NO")
return
t = int(input())
for _ in range(t):
solve()
How to check if an element $$$x$$$ is stable? For an element $$$p_i$$$, we only care about whether $$$p_i \lt x$$$, $$$p_i=x$$$ or $$$p_i \gt x$$$.
If an element is not stable, we can choose $$$m$$$ correctly in the first step to exclude $$$x$$$ from interval $$$[l,r]$$$.
By Caylex.
def solve():
n = int(input())
s = str(input())
l = 0
p = []
for i in range(n):
p.append(i + 1)
while l < n:
if s[l] == "1":
l += 1
continue
r = l
while r + 1 < n and s[r + 1] == "0":
r += 1
if r - l + 1 == 1:
print("NO")
return
ok = 1
for i in range(l, r):
p[i] = i + 2
p[r] = l + 1
l = r + 1
print("YES")
for i in range(n):
print(p[i], end=" ")
print()
return
t = int(input())
for _ in range(t):
solve()
2146D1 - Max Sum OR (Easy Version)
Try a few cases by hand or guess by the samples, what's the maximized answer for $$$l=0,r=n$$$?
The answer is $$$n(n+1)$$$. Actually, as $$$x\mid y\le x+y$$$, so the upper bound for the answer is $$$\sum (a_i+b_i)=n(n+1)$$$. And we are going to reach the upper bound.
We need to make the bitwise AND of $$$a_i$$$ and $$$b_i$$$ all equal to $$$0$$$. Let's remind you that the bitwise AND of $$$x$$$ and $$$2^k-1-x$$$ is $$$0$$$ for $$$0\le x \lt 2^k$$$. We can try to pair integers $$$x$$$ and $$$y$$$ by letting $$$a_x=y,a_y=x$$$.
Construct from the back.
By Caylex.
def solve():
l, r = map(int, input().split())
pw = 1
ans = 0
while pw < r:
pw = pw << 1 | 1
s = set()
for i in range(l, r + 1):
s.add(i)
a = [0] * (r + 1)
for i in range(r, l - 1, -1):
while pw - i not in s:
pw >>= 1
a[i] = pw - i
ans += i | a[i]
s.remove(pw - i)
print(ans)
print(*a[l : r + 1])
return
t = int(input())
for _ in range(t):
solve()
2146D2 - Max Sum OR (Hard Version)
Let's consider from the highest bits to the lowest bits. If the highest bits of $$$l$$$ and $$$r$$$ are the same, we can just ignore this bit and go on to a lower bit. We can still try to pair integers $$$x$$$ and $$$y$$$ by letting $$$a_x=y,a_y=x$$$.
Consider the highest bit that $$$l$$$ and $$$r$$$ differs. There exist an integer $$$t$$$ that this bit of $$$l\ldots t-1$$$ are $$$0$$$ and this bit of $$$t\ldots r$$$ are $$$1$$$. We need to pair a $$$0$$$ with a $$$1$$$ as more as possible while keeping the bitwise AND of lower bits small. Can we turn it into a smaller subproblem?
In D1, it is optimal to pair $$$x$$$ with $$$2^k-1-x$$$. Here, for interval $$$[l,r]$$$ and integer $$$t$$$ defined in Hint2, it is optimal to pair $$$x$$$ with $$$2t-1-x$$$.
By Caylex.
def g(x, j):
return x >> j & 1
def solve():
L, R = map(int, input().split())
a = [0] * (R - L + 1)
def solve(l, r, j):
if l > r:
return
if l == r:
a[l - L] = r
return
mid = l
while mid + 1 <= r and g(mid + 1, j) == g(l, j):
mid += 1
if mid == r:
solve(l, r, j - 1)
return
tl = mid + 1
tr = mid
while tl - 1 >= l and tr + 1 <= r:
tl -= 1
tr += 1
a[tl - L] = tr
a[tr - L] = tl
solve(l, tl - 1, j - 1)
solve(tr + 1, r, j - 1)
return
solve(L, R, 29)
ans = 0
for i in range(L, R + 1):
ans += a[i - L] | i
print(ans)
print(*a)
return
t = int(input())
for _ in range(t):
solve()
It turns out that we can solve it greedily from the lowest bit to the highest bit. For each element in $$$[l,r]$$$, let's reverse its binary representation and insert it into a 01-trie. Then for each index $$$i$$$, we can do dfs on the trie while trying to keep every bit different with $$$i$$$. Formally, each step we try to go to the opposite side of each bit of $$$i$$$, and go on the other side if that subtree is empty.
We can prove that this gives the same construction with the other method constructing from the higher bits. You can read the implementation for better understanding.
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define REP(i,b,e) for(int i=(b);i<(int)(e);++i)
int l,r;
int tot;
int son[6000005][2],cnt[6000005];
void Main() {
cin>>l>>r;
tot=1;
son[0][0]=son[0][1]=-1;
REP(i,l,r+1){
int x=0;
REP(j,0,30){
int &p=son[x][(i>>j)&1];
if(p==-1)p=tot++,cnt[p]=0,son[p][0]=son[p][1]=-1;
x=p;++cnt[x];
}
}
int ans=0;
vector<int>res;
REP(i,l,r+1){
int x=0,t=0;
REP(j,0,30){
int o=!((i>>j)&1);
if(son[x][o]==-1||!cnt[son[x][o]])o=!o;
t|=o<<j;
x=son[x][o];--cnt[x];
}
res.pb(t);ans+=i|t;
}
cout<<ans<<'\n';
for(auto i:res)cout<<i<<' ';
cout<<'\n';
}
void TC() {
int tc=1;
cin>>tc;
while(tc--){
Main();
}
}
signed main() {
return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
}
/*
1. CLEAR the arrays (ESPECIALLY multitests)
2. DELETE useless output
*/
2146E - Yet Another MEX Problem
For an array $$$b$$$ and an integer $$$x$$$ that does not appear in $$$b$$$, let $$$g(b,x)$$$ be the number of elements in $$$b$$$ that is greater than $$$x$$$. Then the weight of $$$b$$$ equals to $$$g(b,\rm{mex}(b))$$$. However, when $$$x\neq \rm{mex}(b)$$$, what will happen to $$$g(b,x)$$$?
The value of $$$g(b,x)$$$ is always smaller than or equal to $$$g(b,\rm{mex}(b))$$$, because when $$$x$$$ does not appear in $$$b$$$, letting $$$x=\rm{mex}(b)$$$ is optimal to maximize $$$g(b,x)$$$.
For a fixed right endpoint $$$r$$$, let's enumerate over all the $$$x$$$ and maximize $$$g(a[l\dots r],x)$$$ while keeping $$$x$$$ no occurred in $$$a[l\dots r]$$$. It's clear that the value is maximized for $$$x$$$ if $$$l$$$ equals the last occurrence of $$$x$$$ plus $$$1$$$.
Use a segment tree to maintain the answer for each $$$x$$$.
By LMydd0225.
#include<bits/stdc++.h>
using namespace std;
#define all(v) v.begin(),v.end()
#define pb push_back
#define REP(i,b,e) for(int i=(b);i<(int)(e);++i)
int n;
int a[300005];
struct ds{
int seg[1200005],tag[1200005];
void build(int l,int r,int p){
seg[p]=tag[p]=0;
if(l==r)return;
int m=(l+r)>>1;
build(l,m,p*2+1);build(m+1,r,p*2+2);
}
void update(int l,int r,int s,int t,int p){
if(l<=s&&t<=r){
++seg[p];++tag[p];
return;
}
int m=(s+t)>>1;
if(m>=l)update(l,r,s,m,p*2+1);
if(m<r)update(l,r,m+1,t,p*2+2);
seg[p]=max(seg[p*2+1],seg[p*2+2])+tag[p];
}
void point(int pos,int l,int r,int p,int val=0){
if(l==r)return seg[p]=-val,void();
int m=(l+r)>>1;
val+=tag[p];
if(m>=pos)point(pos,l,m,p*2+1,val);
else point(pos,m+1,r,p*2+2,val);
seg[p]=max(seg[p*2+1],seg[p*2+2])+tag[p];
}
}seg;
void Main() {
cin>>n;
REP(i,0,n)cin>>a[i];
seg.build(0,n,0);
REP(i,0,n){
seg.update(0,a[i],0,n,0);
seg.point(a[i],0,n,0);
cout<<seg.seg[0]<<' ';
}
cout<<'\n';
}
void TC() {
int tc=1;
cin>>tc;
while(tc--){
Main();
cout.flush();
}
}
signed main() {
return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
}
/*
1. CLEAR the arrays (ESPECIALLY multitests)
2. DELETE useless output
*/
There's a harder version of the problem. Can you solve it?
There're $$$q$$$ queries: $$$x,y$$$. Find $$$\max_{x\le l\le r\le y}w(l,r)$$$. $$$n,q\le 3\cdot 10^5$$$.
Let's focus on bubble sort first. For an element $$$p_x$$$, how many rounds does it take to make all the numbers before the position small than $$$p_x$$$?
Count the number of integers $$$i$$$ such that $$$i \lt x$$$ and $$$p_i \gt p_x$$$. In one round of bubble sort, exactly one of that sort of element will be moved to the right of $$$p_x$$$.
Try to count something else instead of permutations $$$p$$$. Can you come up with an $$$O(n^2)$$$ dynamic programming method?
The number of restrictions is small ($$$m\le 1000$$$). Can we decrease the number of states from $$$O(n^2)$$$ to $$$O(nm)$$$ and $$$O(m^2)$$$? How to calculate the coefficients then?
By LMydd0225.
#include<bits/stdc++.h>
using namespace std;
#define MOD 998244353
#define speMOD 2933256077ll
#define int long long
#define pii pair<int,int>
#define all(v) v.begin(),v.end()
#define pb push_back
#define REP(i,b,e) for(int i=(b);i<(int)(e);++i)
#define over(x) {cout<<(x)<<endl;return;}
#define lowbit(x) ((x)&(-(x)))
#define cntbit(x) __builtin_popcount(x)
#define rf(v) shuffle(all(v),sd);
#define deal(v) sort(all(v));v.erase(unique(v.begin(),v.end()),v.end())
#define lbound(v,x) lower_bound(all(v),x)-v.begin()
int qpow(int a,int b,int m=MOD,int res=1){
a%=m;
while(b>0)res=(b&1)?(res*a%m):(res),a=a*a%m,b>>=1;
return res;
}
int fac[2000005],inv[2000005];
void init(int n){
fac[0]=inv[0]=1;
REP(i,1,n+1)fac[i]=fac[i-1]*i%MOD;
inv[n]=qpow(fac[n],MOD-2);
for(int i=n-1;i>=1;--i)inv[i]=inv[i+1]*(i+1)%MOD;
}
int binom(int x,int y){
return x<y||y<0? 0:fac[x]*inv[y]%MOD*inv[x-y]%MOD;
}
struct restr{
int l,r,k;
};
int n,m;
int r1[1000005],r2[1000005];
int dp[10005],sum[10005];
int qry1(int l,int r,int k){
if(k<l)return qpow(k+1,r-l+1);
if(k>r)return fac[r+1]*inv[l]%MOD;
return fac[k+1]*inv[l]%MOD*qpow(k+1,r-k)%MOD;
}
int qry2(int l,int r,int k,int x){
return (qry1(l,r,k)+MOD-qry1(l,r,x))%MOD;
}
void Main() {
cin>>n>>m;
vector<int>v;vector<restr>a;
vector<int>t;
REP(i,0,m){
int k,l,r;
cin>>k>>l>>r;
--l;
if(l>=0)v.pb(l);
if(r<n)v.pb(r);
t.pb(k);
a.pb({l,r,k});
}
v.pb(n-1);t.pb(-1);t.pb(n-1);
deal(v);deal(t);
for(auto i:v)r1[i]=t.size()-1,r2[i]=0;
for(auto i:a){
if(i.k==n-1&&i.r<n-1)over(0)
if(i.l>=0)r1[i.l]=min(r1[i.l],lbound(t,i.k));
if(i.r<n)r2[i.r]=max(r2[i.r],lbound(t,i.k));
}
int lst=0,m=t.size();dp[1]=1;REP(i,2,m+1)dp[i]=0;
for(auto i:v){
REP(j,1,m)sum[j]=dp[j];
REP(j,2,m)(sum[j]+=sum[j-1])%=MOD;
REP(j,1,m)if(j>r2[i]&&j<=r1[i]){
dp[j]=(dp[j]*qry1(lst,i,t[j])+sum[j-1]*qry2(lst,i,t[j],t[j-1]))%MOD;
}else dp[j]=0;
lst=i+1;
}
int res=0;
REP(j,1,m+1)(res+=dp[j])%=MOD;
cout<<res<<endl;
}
void TC() {
init(1000000);
int tc=1;
cin>>tc;
while(tc--){
Main();
cout.flush();
}
}
signed main() {
return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
}
/*
1. CLEAR the arrays (ESPECIALLY multitests)
2. DELETE useless output
*/








We should appreciate fast editorials :))
Thanks for the fast editorial! (Maybe the fastest)
Thanks for fast editorial
FAST EDITORIAL!! Thanks for the contest :)
Appreciations for the fast editorial!
P.S: E was so good ( submitting it just 3 seconds before made the adrenaline rush worth it :D) Loved the contest!
insanely fast editorial ty
couldn't do B because I wasn't convinced iterating over sets individually was fastest D:
Yes such problems always require reading the constraints thoroughly before solving. This has happened with me before. I learnt my lesson last time
How to solve D with trie?
i am also waiting for trie solution
get max_xor from binary trie and this is my solution in contest 339772492
339778312
Storing number from low to high bit is correct. (D2 will fail for your solution). Reason Example
will this same approach work in the case of minimizing the sigma(ai&bi) .please help this question is really good .I think it should
https://mirror.codeforces.com/contest/2146/submission/340031280 Trie solution for D1
https://mirror.codeforces.com/contest/2146/submission/340035255 Trie solution for D2
ultra fast editorial
WOW faster than nasa's internet speed!
fast editorials!
Not able to submit code in first ~15 minutes.
During this period of time, the judge system is still testing the solutions and using all (?) of their resources for it. Once all of the solutions have been rejudged, you will be able to submit again...
I meant I cannot submit code during the first 15 minutes of the contest. The submission page is totally frozen and I cannot paste my code.
really?? Wow, that's pretty strange. I guess for future cases like this you could use the mirror site/submit as file...
editorials with HINTS are sooo sooo good for practice !!
In C's editorial it is mentioned that we can reverse [l,r] but it length is odd won't it be incorrect because for middle elements p[x]=x and it will be stable then
for every s[i] = '0' either there should be smaller element to its right or larger element to its left , if one of the condition hold true then it is fine , when p[x] =x in the case you mention then there are still elements to its right which are smaller then x , this is the reason why it works.
that is only in the case when you guess m = x randomly. to be stable it needs to hold in all cases.
Can D be solved with bit Trie?
Yes, i used trie for D1, but couldn't solve D2 :(
Thank you. ill read up your soln. I couldn't pinpoint how it will be used, so wasted time there.
339778312
Simple solution. And also don't miss the fact we are storing number from low to high bit. Reason
I solved both with trie,I thought that's what everyone else would also have done but to my suprise I didn't found any another submission using trie in my friendlist. I used simple binary trie logic which we generally used to find max xor of an array with any element x,but instead of moving from msb to lsb Moved from lsb to msb so that Gap is not wasted,by Gap mean like in 100 and 001 if we take these two then or will be 101 hence there is 0 between ones which is Gap in my logic.
respect++ for fast editorial
Can someone explain problem E more clearly?
Let ans[x] = answer if MEX = x.
Move from left to right. At i'th step we have ans[] array calculated for all elements to the left of i. Now need to update array ans[] for current i:
ans[a[i]] = 0 because since a[i] mandatory exists (in every subarray (l, i) ), MEX can not be = a[i];
ans[x] for x < a[i] gets increased by 1 because if MEX x < a[i], then appending a[i] does not change MEX, but adds 1 to answer;
ans[x] for x > a[i] remains the same, because appending a[i] does not change MEX, but doesn't change the answer.
To implement it in O(N * logN) a powerful data structure is needed. I've used segment tree with lazy propagation, but may be there are other options.
oooh, i got it, it wasn't that complex
thanks for such clear explanation!
here's the implementation — https://mirror.codeforces.com/contest/2146/submission/344768914
Solution link using Trie Bit for D1 & D2
Build the trie from $$$2$$$ power of $$$0$$$ to $$$30$$$, then iterate elements from $$$L$$$ to $$$R$$$ and greedily search for the opposite bit
How does it work? I tried to greedily search from $$$30$$$ to $$$0$$$ but failed. Could you explain why from low to high works?
I'm not sure either, i also tried from 30 to 0 at first, but it didnt pass the samples so i just reversed it and it ACed (literally prove by AC)
I have the same. Tried D1 from the greatest bit and failed on D2. But after i tried from the least bit and it works! Idk know why, lol.
The reason is that when we traverse from high to low, if a desired bit is not present, we switch paths to take an available number. However, this may lead us to a number with fewer bits. On the other hand, when traversing from low to high, the correct number is retrieved.
P.S. — Example
Can you explain why traversing from 0 to 30 find a number with more set bits compare to 30 to 0 because in both approach we are changing path as when we required it.
If this can help. Comment
Thank you so much for really good problems and the fast editorial.
Didn't you wanted to say, in tutorial of problem E, that we want to increase b_i by 1 for all i < a_r ?
Fixed, thanks.
nice contest, speedforces
oh just compare my time limit submission with my accepted submission on D2
i can not sleep tonight
How is checker for problem C made?
Edit:Understood
for problem tags on C, there are 8 binary search tags . Is that going to be fixed ?
the fastest round I have ever witnessed!!!
For D2 I did trie + heap.
https://mirror.codeforces.com/contest/2146/submission/339774331
Why using heap. I did with trie only. 339778312
Hi. Can you explain why it is optimal to solve it from the lowest bit to the highest bit?
Here is a case where high to low bit will fail.
l = 3, r = 6
high to low trie -> 26
low to high trie -> 28
Thanks for your hack, but I just can't understand why it is optimal from low bit to high bit. Could you make a explanation?
If insert numbers into trie from high bit to low bit, and get the answer from $$$l$$$ to $$$r$$$, it will get WA on $$$[3, 6]$$$ where the correct answer is $$$28$$$, but $$$26$$$ is given.
If insert numbers into trie from high bit to low bit, and get the answer from $$$r$$$ to $$$l$$$, it will get WA on $$$[1, 4]$$$ where the correct answer is $$$20$$$, but $$$18$$$ is given.
I solved D1 with the method of traversing from high bit to low bit and get the answer from $$$r$$$ to $$$l$$$ but failed on D2. It's really confusing.
OR is monotone but not lexicographic — adding a
1in any bit helps, but there's no strict ordering where higher-bit wins over all lower bits combined. MSB-first greedily optimizes the current bit or breaks ties locally; but maximizing total number of1bits (or numeric value of OR) can require sacrificing an MSB tie to gain many 1s in lower bits. That requires deferring decisions about higher bits until you’ve examined lower bits → exactly what LSB-first does.Also in D1, all numbers $$$[0,r]$$$ are present. Therefore, all numbers' XOR are present, but in D2 as the exact XOR can be absent, can lead to picking up wrong number.
But hey can you prove that going from LSB to MSB is always optimal, you showed a case where MSB to LSB fails. But can you prove there exists no case where LSB to MSB fails.
suppose there exist a case where sacrificing a higher a bit is not optimal but we won't know about it because we already made the decision before reaching highest bit
Sorry to disappoint you mate, I don't have a concrete proof for this. I did this question purely based on my intuitions which I wrote above, I solved D1 using different approach not trie-based.
Seems that,to some degree,there exists some equivalence. Consider the solution in the editorial,assuming that the current interval is [l,r] with the t defined in the solution. Without loss of generality,let length of [l,t)<[t,r].With the way in the solution,we pair each x of [l,t) with 2t-1-x. For certain x,if x+t<=r,assuming it finally match with y,then we can swap the matches.To be specific,in the solution it matches like (x,2t-1-x) and (x+t,y),however the result of (x,y) and (x+t,2t-1-x) is the same,because it holds that y&t=t.That's the stage of t,and for later stages with t'<t,it is obvious that the swap holds. To be vivid,assuming we have a values with t and b values without t,we only have to assure we get min(a,b)*t,but how we get it doesn't count. Thus,your solution is clearly right.On the other hand,if we start from the highest bit,for [l,r],if it could be described as [l,t),[t,2t-l-1],[2t-l,r] where r<t+l,then if we greedily try r,r-1,...,we get a wrong solution(where [2t-l,r] match with certian value in [l,t),get the t,however lose t'<t,and the swap mentioned above is no longer equivalent)
I used high to low trie and it still passed.
343100466
I did without using any of them. https://mirror.codeforces.com/contest/2146/submission/339810751
Most of the people had same thought process. I recently solved a problem with BitTrie + remove() method. So, I tried with this and I think this is easier.
Can you please explain your code?
for D2 I did just greedy O(n * 33) https://mirror.codeforces.com/contest/2146/submission/339764552
Oh WHOA, that was fast.
I mean I checked in after 2-3 hours and it's already here, damn!
Great problems!
Can Anybody help with why my code is giving the wrong answer? I was very convinced that it should work, but it's failing somewhere on test case 2 for Problem C — Rabbits, and I badly want to see where it's breaking.
What I am doing is basically seeing where the current rabbit is facing, if its face is to its left — In this case, I will need some right counter which means rabit facing left.
If the current rabbit can face either left or right, or it's not decided yet, I will mark undecided so that I can resolve it based on the next rabbit. If the next rabbit is undecided too, I'll pass the counter undecided until it's resolved.
Solution
Thanks for the tutorial. It’s really useful.
good contest
I love problem C
In problem B
Original problem deals with n sets S1, S2, ..., Sn and asks whether there are at least three ways to choose some sets so that every integer from 1 to m appears in at least one chosen set.
Now, suppose instead of sets, we are given n arrays that may contain duplicate elements.
How should we approach this problem efficiently when arrays may have duplicates?
Convert vector into set and solve the problem...
i want to know how to solve this problem without converting into set.
then in that case we need to know all the frequencies of that particular set
Ok got it, thanks
I'd solved A,B,D but with problem C, I'm still struggling as I was not able to understand it even now! What I got is if Si==1 then in Pi=i and for all other Pi!=i. 1 more case is if count of 1's is even then print NO. What is this problem
As for the trie solution to problem D, can anyone explain why it is optimal to solve it greedily from the lowest bit to the highest bit?
Example
Cool round, thx!
In the Editorial of problem C, in second point shouldn't l become m+1 instead of r = m-1
Fixed, thanks.
In the Editorial of D2,I find that the example of [11,16] is not the biggest one. It's less than [12,11,16,15,14,13].A small mistake.
But yours is smaller.
Sorry, I made a mistake. You are right.
There is one more way to prove the solution for Problem D1 using induction and the following two observations:
1 → If we make a partition between a number x = (power of 2) and
x - 1, then with respect to this partition, the pairs(x - 1 , x), (x - 2, x + 1), …will be complements of each other. For example: (7, 8), (6, 9), (5, 10) ............. wrt. to partition between (7, 8).2 → If we take numbers 0, 1, 2, 3, 4, 5, …, r and let x = (maximum power of two such that x ≤ r), then the (count of numbers from x to r) will always be ≤ (count of numbers less than x). More Formally
(r - x + 1) <= (x + 1). In short, there are always x + 1 elements from 0 to x — 1 in left, while on the right side (including x) there can be at most x elements. Otherwise, x would become the next power of two, which contradicts our assumption.For example, if r =
15:(Maximum power of 2) ≤ r ⇒ x =
8Count of numbers from x to r =
15 - 8 + 1 = 8Count of numbers from 0 to x — 1 =
8Now, just make a partition between x = (max power of 2 ≤ r) and x — 1, do the pairing as in point 1. From point 2, the elements on the right side of the partition will always end first. So, after the first iteration of pairing, we again get a new unmatched array → (0, 1, 2, 3 ....... x).
Now You have the similar subproblem will lesser value of r.
for example if r = 10
Problem E is nice . I tried — like extending ans[i] to ans[i+1] from left to right , right to left . consider all mexs . iterating from left to right . form segments of the bigger number increasing the answer ; nothing properly clicked like the stuff being done in editorial . Thanks .
can anyone tell why author's code for D1 is giving TLE for input t = 1 l = 4, r = 5
Time complexity : $$$O(n\log n)$$$ 340097439
I come a solution different to author,the idea is complement.
First when i don't know how to do,then i try something greedily,let say $$$x$$$ is a number between $$$l=0$$$ and $$$r$$$ which is $$$l=0\le x \le r$$$,if i want to produce the optimal sulution i should let $$$x$$$ and ~$$$x$$$ combine to do bitwise or,~$$$x$$$ denoted 1's complement of $$$x$$$,why?The reason is according to the bitwise or defination at least one $$$1$$$ will leading the result become $$$1$$$,so in optimize way we should use $$$0$$$ to bitwise or with $$$1$$$,instead of $$$1$$$ bitwise or with $$$1$$$,until now i don't know is that possible to make $$$x$$$ can always combine with it complement or not then i try to simulation,i accidentally found that there is working.
Algorithm
Let $$$k$$$ be the number such that $$$2^k \le r \lt 2^{k+1}$$$.The algorithm is work as below,First let $$$x \in [2^k,r]$$$ and the $$$\text{mask}$$$ be $$$\underbrace{1111\dots 111}_{k+1}$$$ , and $$$\oplus$$$ denoted bitwise xor then $$$x$$$ and $$$x \oplus \text{mask}$$$ will combine together,then after this,let $$$y \in [l=0,2^{k}-1]$$$ and the $$$\text{mask}$$$ be $$$\underbrace{1111\dots 111}_{k}$$$ , if $$$y$$$ and $$$y\oplus mask$$$ haven't been combine then they combine together,otherwise continue. At the end,there may some remain element doesn't combine with other and the element are $$$[l=0,r'\lt r]$$$,every iteration will decrease the most significant bit of $$$r$$$ at least one bit,when $$$r == 2^m-1$$$ then directly $$$x\in [l=0,r]$$$,$$$x$$$ combine with $$$2^m-1-x$$$.
Proof
$$$\text{Why when }2^k \le r \lt 2^{k+1} \text{ then } x\in [2^k,r]\text{ always find a 1's complement?}$$$
$$$\text{Answer : since } 2^k \le r \lt 2^{k+1} \text{ then }0 \le r-2^k \lt 2\cdot 2^k - 2^k \text{ which is } 0 \le r-2^k \lt 2^k\text{ the element below }2^k\text{ is more than }r-2^k$$$
$$$\text{Why every iteration will decrease at least one most significant bit?}$$$
$$$\text{Answer : From the previous question,we already prove that every }x\in[2^k,r]\text{ will exactly find one 1's complement to combine,so after the remain element will decrease at least one most significant bit}$$$
Now I also love problem E
Wrong binary search gave so many chills. Learnt a lot thank you!
Can someone explain how to solve D1? Using trees
trie ig
(not my solution I read that in the comments section) so if you really want to know how they solved it you'd have to read the comments