http://acm.hdu.edu.cn/showproblem.php?pid=6579
There is an integer sequence a of length n and there are two kinds of operations:
- 0 l r: select some numbers from al...ar
- so that their xor sum is maximum, and print the maximum value.
- 1 x: append x
- to the end of the sequence and let n=n+1
- .
Input
There are multiple test cases. The first line of input contains an integer T(T≤10)
, indicating the number of test cases.
For each test case:
The first line contains two integers n,m(1≤n≤5×105,1≤m≤5×105), the number of integers initially in the sequence and the number of operations.
The second line contains n integers a1,a2,...,an(0≤ai<230), denoting the initial sequence.
Each of the next m lines contains one of the operations given above.
It's guaranteed that ∑n≤106,∑m≤106,0≤x<230.
And operations will be encrypted. You need to decode the operations as follows, where lastans denotes the answer to the last type 0 operation and is initially zero:
For every type 0 operation, let l=(l xor lastans)mod n + 1, r=(r xor lastans)mod n + 1, and then swap(l, r) if l>r.
For every type 1 operation, let x=x xor lastans.Output
For each type 0 operation, please output the maximum xor sum in a single line.
Sample Input
1 3 3 0 1 2 0 1 1 1 3 0 3 4
Sample Output
1 3
题目大意:给n个数,m个操作,有两种操作:(1)0 l r,查询[l,r]的异或最大值。(2)1 x 给原序列末端加上一个x。这个操作是在线的,要求:l=l^ans%n+1,r=r^ans%n+1,x=x^ans。(ans是上次查询的答案)
思路:区间线性基。注意异或的优先级比较低,要带括号。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=1e6+5;
int b[maxn][35],pos[maxn][35],base[35];
inline bool insert(int h,int x)//维护区间[1,h]内的线性基
{
for(int i=0;i<=30;i++)
b[h][i]=b[h-1][i],pos[h][i]=pos[h-1][i];
int tmp=h;
for(int i=30;i>=0;i--)
{
if(x&base[i])
{
if(b[h][i])
{
if(pos[h][i]<tmp)
{
swap(pos[h][i],tmp);
swap(b[h][i],x);
}
x^=b[h][i];
}
else
{
b[h][i]=x;
pos[h][i]=tmp;
return 1;
}
}
}
return 0;
}
int get_max(int l,int r)//求区间[l,r]内的最大异或值
{
int ans=0;
for(int i=30;i>=0;i--)
if(pos[r][i]>=l&&(ans^b[r][i])>ans)
ans^=b[r][i];
return ans;
}
int main()
{
for(int i=0;i<=30;i++)
base[i]=1ll<<i;
int t;
scanf("%d",&t);
int n,m,op,l,r,ans=0;
while(t--)
{
ans=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&op);
insert(i,op);
}
for(int i=0;i<m;i++)
{
scanf("%d",&op);
if(!op)
{
scanf("%d%d",&l,&r);
l=(l^ans)%n+1;
r=(r^ans)%n+1;
if(l>r)
swap(l,r);
ans=get_max(l,r);
printf("%d\n",ans);
}
else
{
scanf("%d",&l);
l^=ans;
insert(++n,l);
}
}
}
return 0;
}