xor
2.1 Description
给出n 个数,Q 次询问,每次问[l,r] 中最大连续异或和。为了体现在线操作,对于每次询问
(x,y):
l = min(((x + lastans) mod n) + 1; ((y + lastans) mod n) + 1)
r = max(((x + lastans) mod n) + 1; ((y + lastans) mod n) + 1)
2.2 Input
第一行为两个整数n,m,分别表示数的个数和询问次数。
接下来一行n 个数,再接下来m 行,每行两个数x,y,表示给出询问(x,y),通过上述操作得
到l 和r,查询[l,r] 中最大连续异或和。
2.3 Output
输出m 行,每行一个整数表示该次询问的答案。
2.4 Sample Input
3 3
1 4 3
0 1
0 1
4 3
2.5 Sample Output
5
7
7
2.6 Note
对于30%的数据,n 500;Q 500。
对于100%的数据,n 12000;Q 6000 , 给出的数均在signed long int 范围内,且均为非负
数。
分块预处理出块到点的最大连续异或,用可持续化trie树维护区间最大异或查询操作(建树用前缀异或建)。分块时**注意:因为计算 (l,r) ( l , r ) 区间内最大异或是要把 l−1 l − 1 和 r r 异或起来,所以用到的实际上是和 root[r] r o o t [ r ] 。
#include<iostream>
#include<cstdio>
#include<cmath>
#define ll long long
using namespace std;
int n, m;
int zz[12005], pre[12005];
int tail, son[10000005][2], siz[10000005], blo[12005], dp[120][12005], root[12005], block;
int max ( int a, int b ) { return a > b ? a : b; }
int min ( int a, int b ) { return a < b ? a : b; }
void insert ( int &nd, int pnd, ll x, int qwq ) {//位数统一为31位建trie树
nd = ++ tail;
son[nd][0] = son[pnd][0];
son[nd][1] = son[pnd][1];
siz[nd] = siz[pnd] + 1;
if ( qwq == -1 ) return ;
int t = ( x >> qwq ) & 1;
insert ( son[nd][t], son[pnd][t], x, qwq - 1 );
}
int query_block ( int x, int lnd, int rnd ) {
int res = 0, nd = 0;
for ( int qwq = 31; qwq >= 0; qwq -- ) {
int d = ( x >> qwq ) & 1;
int ls = son[lnd][d^1], rs = son[rnd][d^1];
if( siz[rs] - siz[ls] > 0 ) { //类似主席树的查询
res |= ( 1 << qwq );
lnd = ls;
rnd = rs;
}
else lnd = son[lnd][d], rnd = son[rnd][d];
}
return res;
}
void init ( ) {
int tot;
block = sqrt ( n );
tot = n / block;
if ( n % block ) tot ++;
for ( int i = 1; i <= tot; i ++ ) {
int st = ( i - 1 ) * block + 1, ed = min ( i * block, n );
for ( int j = st; j <= ed; j ++ )
blo[j] = i;
}
for ( int i = 1; i <= tot; i ++ ) {
int st = ( i - 1 ) * block + 1;
for ( int j = st; j <= n; j ++ ) {
dp[i][j] = max ( pre[j] ^ pre[st-1], dp[i][j-1] );
dp[i][j] = max ( dp[i][j], query_block ( pre[j], root[st-1], root[j] ) );
}
}
}
int query ( int l, int r ) {
int st = blo[--l], res = 0; ///用l-1去开始比较
if ( blo[r] > st ) res = dp[st+1][r]; //查询从后面一个块开始的
for ( int i = l; i <= min ( r, st * block ); i ++ )
res = max ( res, query_block ( pre[i], root[l-1], root[r] ) );
return res;
}
int main ( ) {
freopen ( "xor.in", "r", stdin );
freopen ( "xor.out", "w", stdout );
scanf ( "%d%d", &n, &m );
int lastans = 0;
for ( int i = 1; i <= n; i ++ ) {
scanf ( "%d", &zz[i] );
pre[i] = pre[i-1] ^ zz[i];
insert ( root[i], root[i-1], pre[i], 31 );
}
init ( );
for ( int i = 1; i <= m; i ++ ) {
int x, y;
scanf ( "%d%d", &x, &y );
int a = ( x + lastans ) % n + 1, b = ( y + lastans ) % n + 1;
int l = min ( a, b ), r = max ( a, b );
lastans = query ( l, r );
printf ( "%d\n", lastans );
}
return 0;
}