题目
找出最短的连续子序列,满足异或和不小于k
题目
思路
01字典树可以求数列间任意两数的异或最大值,将两个数换成前缀异或就可以求连续区间的最大异或值。
用
l
、
r
l、r
l、r表示当前的区间,将前缀和不断加入01字典树中,
r
r
r不断
+
1
+1
+1,如果这个区间存在异或最大值
>
=
k
>=k
>=k,说明以
r
r
r为右端点下标的某段区间满足区间异或和
>
=
k
>=k
>=k,就令
n
e
w
l
newl
newl从
r
r
r开始左移,寻找最近的满足区间异或和
>
=
k
>=k
>=k的
n
e
w
l
newl
newl,然后将
l
l
l到
n
e
w
l
newl
newl之间的区间从01字典树中删除,然后将
l
l
l移到
n
e
w
l
newl
newl处。
再找到第一个满足区间异或和
>
=
k
>=k
>=k的序列之后记录下它的长度,因为要求最小值,所以可以将长度固定下来,右移
r
r
r的同时不断右移
l
l
l,发现有更短的序列之后维护最短长度。
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn =3e6+5;
int tire[31*maxn][2];
int tot;
int ans;
int judge[31*maxn];
ll re_sum[31*maxn];
const int INF = 0x3f3f3f3f;
void insert_delete(ll x,int add)//插入和删除操作
{
int root=0;
for(int i=31; i>=0; i--)
{
int id=x>>i&1;
if(!tire[root][id]){
tire[root][id]=++tot;
tire[tot][0] = tire[tot][1] = 0;
judge[tot] = 0;
}
root=tire[root][id];
judge[root]+=add;
}
re_sum[root]=x;
}
ll find(ll x)
{
int root=0;
for(int i=31; i>=0; i--)
{
int id=x>>i&1;
if(judge[tire[root][id^1]]>0)//贪心思路
root=tire[root][id^1];
else
root=tire[root][id];
}
return re_sum[root];
}
ll a[100010],pre[100010];
signed main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n,t;
cin>>t;
while(t--)
{
tot=0;
int n;
ll k;
cin>>n>>k;
pre[0]=0;
tire[0][1]=tire[0][0]=0;
for(int i=1;i<=n;i++){
cin>>a[i];
pre[i]=pre[i-1]^a[i];
}
int l=1;
bool f=0;
insert_delete(0,1);
int ansl=0,ansr=0,ans=INF;
bool flag=0;
int s=1;
for(int i=1;i<=n;i++){
ll q = find(pre[i]);
insert_delete(pre[i],1);
// cout<<"! "<<q<<" "<<(q^pre[i])<<endl;
ll qq=q;
q^=pre[i];
if(q>=k){
flag=1;
s=l;
for(int j=i;j>=l&&(i-j+1<=ans);j--){
if((pre[j-1]^pre[i])>=k){
// cout<<pre[j-1]<<" "<<pre[i]<<" "<<(pre[j-1]^pre[i])<<" "<<k<<endl;
l=j;
break;
}
}
// cout<<"!! "<<qq<<" "<<(q^pre[i-1])<<" "<<l<<" "<<pre[l]<<endl;
for(int j=s;j<l;j++){
insert_delete(pre[j],-1);
}
// cout<<l<<" "<<i<<" "<<ans<<" "<<q<<endl;
if(i-l+1<ans){
ansl=l,ansr=i,ans=i-l+1;
}
}
else if(flag){
insert_delete(pre[l],-1);
l++;
}
}
if(flag) cout<<ansl<<" "<<ansr<<endl;
else cout<<"-1"<<endl;
for(int i=l;i<=n;i++) insert_delete(pre[i],-1);
}
return 0;
}