I am using binary search + prefix sum method but getting WA for once case only
I read through this thread and saw the testcase:
1
6
1 1 2 2 4 4
But my code gives -1 for this which I think is correct , so thats not the problem.
Can someone please help me find the error in my code. Thank you.
#include <bits/stdc++.h>
using namespace std;
int rangeOr (vector<vector<int>> &ora,int l,int r){
int ans=0;
for(int j=0;j<32;j++){
if(l==0){
if(ora[r][j]>0)
ans |= (1<<j);
}
else{
if(ora[r][j]-ora[l-1][j] > 0)
ans |= (1<<j);
}
}
return ans;
}
bool check(vector<vector<int> > &ora,int len){
int n = ora.size();
for(int i=0;i+len-1<n;i++){
if(i==0){
int lor = rangeOr(ora,0,len-1);
int ror = rangeOr(ora,len,n-1);
if(lor == ror) return 1;
}
else if (i+len==n){
int lor = rangeOr(ora,0,i-1);
int ror = rangeOr(ora,i,n-1);
if(lor == ror) return 1;
}
else{
int left = rangeOr(ora,0,i-1);
int mid = rangeOr(ora,i,i+len-1);
int right = rangeOr(ora,i+len,n-1);
if(mid == (left | right)) return 1;
}
}
return 0;
}
int main(){
int t;cin>>t;
while(t--){
int n; cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++) cin>>a[i];
vector<vector<int> > ora(n,vector<int>(32,0));
for(int j=0;j<32;j++){
for(int i=0;i<n;i++){
if(a[i] & (1<<j)){
ora[i][j]=1;
}
}
}
for(int i=1;i<n;i++){
for(int j=0;j<32;j++){
ora[i][j] += ora[i-1][j];
}
}
int ans=-1;
int lo=1,hi=n-1;
while(lo<=hi){
int mid = lo + (hi-lo)/2;
if(check(ora,mid)){
ans = mid;
lo = mid+1;
}
else
hi = mid-1;
}
cout<<ans<<endl;
}
return 0;
}