您的位置:首页 > 其它

[可持久化Trie] BZOJ3261: 最大异或和

2017-07-13 21:51 357 查看

题意

给定一个非负整数序列 {a},初始长度为 N。

有 M个操作,有以下两种操作类型:

1 、A x:添加操作,表示在序列末尾添加一个数 x,序列的长度 N+1。

2 、Q l r x:询问操作,你需要找到一个位置 p,满足 l<=p<=r,使得:

a[p] xor a[p+1] xor … xor a
xor x 最大,输出最大是多少。

n<=300000

题解

用容斥转换一下,设sum[i]为A数组1~i的异或和,则题目所求即为max(sum[n] ^ sum[i] ^ x),i=[l−1,r−1]

每次 sum[n] ^ x 是定值,所以就相当于找在一个区间中找一个数使得它异或上一个给定的数的值最大。

可持久化Trie就好了。

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=600005;
struct node{
int sz; node* ch[2];
node(node* son=NULL){ sz=0; ch[0]=ch[1]=son; }
} nil, *null=&nil, *rt[maxn];
typedef node* P_node;
void init(){
null->sz=0; null->ch[0]=null->ch[1]=null;
rt[0]=null;
}
void Insert(P_node pre,P_node &p,int val,int now){
p=new node(null);
p->ch[0]=pre->ch[0]; p->ch[1]=pre->ch[1]; p->sz=pre->sz+1;
if(now) Insert(pre->ch[(now&val)?1:0],p->ch[(now&val)?1:0],val,now>>1);
}
int Query(P_node R,P_node L,int val,int now){
if(!now) return 0;
if(R->ch[(now&val)?0:1]->sz - L->ch[(now&val)?0:1]->sz >0)
return now+Query(R->ch[(now&val)?0:1],L->ch[(now&val)?0:1],val,now>>1);
return Query(R->ch[(now&val)?1:0],L->ch[(now&val)?1:0],val,now>>1);
}
int n,Q,sum[maxn];
int main(){
freopen("bzoj3261.in","r",stdin);
freopen("bzoj3261.out","w",stdout);
init();
scanf("%d%d",&n,&Q);
Insert(null,rt[0],0,1<<30);
for(int i=1;i<=n;i++){
scanf("%d",&sum[i]); sum[i]^=sum[i-1];
Insert(rt[i-1],rt[i],sum[i],1<<30);
}
while(Q--){
char ch=getchar(); while(ch!='A'&&ch!='Q') ch=getchar();
if(ch=='A'){
n++; scanf("%d",&sum
); sum
^=sum[n-1];
Insert(rt[n-1],rt
,sum
,1<<30);
} else{
int L,R,x; scanf("%d%d%d",&L,&R,&x);
printf("%d\n",Query(rt[R-1],L-2>=0?rt[L-2]:null,sum
^x,1<<30));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: