【CF 617E】 XOR and Favorite Number (Mo's algorithm)
Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k.
The first line of the input contains integers n, m and k (1 ≤ n, m ≤ 100 000, 0 ≤ k ≤ 1 000 000) — the length of the array, the number of queries and Bob's favorite number respectively.
The second line contains n integers ai (0 ≤ ai ≤ 1 000 000) — Bob's array.
Then m lines follow. The i-th line contains integers li and ri (1 ≤ li ≤ ri ≤ n) — the parameters of the i-th query.
Print m lines, answer the queries in the order they appear in the input.
6 2 3 1 2 1 1 0 3 1 6 3 5
7 0
5 3 1 1 1 1 1 1 1 5 2 4 1 3
9 4 4
In the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query.
In the second sample xor equals 1 for all subarrays of an odd length.
题目大意是找某个区间内连续异或能得到K的区间数
现在先考虑单组区间查询。对于区间[L,R] 可以求个前缀和pre[i] 表示第1~i的数的异或和。这样[L,R]的异或和即为pre[L-1]^pre[R] 换种思路 预存一下pre[L-1]^k 就可以延长它的生命周期。
这样求[L,R]区间内能异或出k的区间数 从L遍历到R 遍历过程中统计遍历过的前缀异或和的个数 当遍历到i时 pre[i]^k出现的次数即为[L,i]中到i的连续的能异或得到k的区间数
这样如果区间向左或向右就可以O(1)的修改 对于多组查询 就可以上莫队算法了
代码如下:
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread() freopen("in.in","r",stdin)
#define fwrite() freopen("out.out","w",stdout)
using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 100100;
const double eps = 1e-8;
//L的分块
int pos[msz];
struct Range
{
int l,r,id;
bool operator < (const struct Range a)const
{
return pos[l] == pos[a.l]? r < a.r: pos[l] < pos[a.l];
}
};
Range rg[msz];
int a[msz];
//统计出现过的异或数
LL cnt[1048576];
LL ans[msz];
LL num;
int n,m,k;
//移动区间边界时更新
void update(int x,int d)
{
if(d < 0)
cnt[k^a[x]] +=d;
num += d*cnt[a[x]];
if(d > 0)
cnt[k^a[x]] +=d;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
int dm = ceil(sqrt(n*1.0));
a[0] = 0;
a[n+1] = 0;
for(int i = 1; i <= n; ++i)
{
scanf("%d",&a[i]);
a[i] ^= a[i-1];
}
for(int i = 0; i < m; ++i)
{
scanf("%d%d",&rg[i].l,&rg[i].r);
rg[i].l--;
pos[rg[i].l] = rg[i].l/dm;
rg[i].id = i;
}
sort(rg,rg+m);
int l = 1,r = 0;
num = 0;
memset(cnt,0,sizeof(cnt));
for(int i = 0; i < m; ++i)
{
int id = rg[i].id;
if(rg[i].l == rg[i].r-1)
{
ans[id] = (a[rg[i].r]^a[rg[i].l]) == k;
continue;
}
while(r < rg[i].r) update(++r,1);
while(r > rg[i].r) update(r--,-1);
while(l < rg[i].l) update(l++,-1);
while(l > rg[i].l) update(--l,1);
ans[id] = num;
}
for(int i = 0; i < m; ++i)
printf("%lld\n",ans[i]);
return 0;
}