Codeforces Round #340 (Div. 2)E-XOR and Favorite Number(莫队算法)

B - XOR and Favorite Number
Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Submit  Status

Description

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.

Input

The first line of the input contains integers nm and k (1 ≤ n, m ≤ 100 0000 ≤ 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.

Output

Print m lines, answer the queries in the order they appear in the input.

Sample Input

Input
6 2 3
1 2 1 1 0 3
1 6
3 5
Output
7
0
Input
5 3 1
1 1 1 1 1
1 5
2 4
1 3
Output
9
4
4

Hint

In the first sample the suitable pairs of i and j for the first query are: (12), (14), (15), (23), (36), (56), (66). 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.


题意:

  给出你n个数,m次查询,要你找出[L,R]异或为k的子区间有多少个。

思路:

  这题思路是首先求出前缀和,所以就会有sum[L-1]^sum[R]==k的公式,但是左边是两个都是不清楚值的,所以要转变一下,

变为sum[R]^k==sum[L-1],这样子我只要求出现在存在多少个sum[L-1]就知道有多少个可以和sum[k]异或为k的了。


AC代码:


#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
#define T 1000000+150
typedef long long ll;

ll Ans[T],ans;
int sum[T],num[1<<20],k,sz;
struct node
{
	int L,R,id;//左右区间,当前是第几次询问
}a[T];

bool cmp(const node& a,const node& b)//分块排序
{
	if((a.L/sz)==(b.L/sz))return a.R<b.R;
	return a.L<b.L;
}

void add(int x)//增加函数
{
	/*
	当前sum[L-1]^sum[R]=k,所以只要知道当前sum[L-1]有多少个
	即有多少个是在[L-1,R]区间异或是等于k的
	*/
	ans += num[sum[x]^k];
	num[sum[x]]++;//增加当前前缀和个数
	//这里后来才加是为了防止增加为本身
}

void sub(int x)//减少函数
{
	num[sum[x]]--;//一个数有可能异或后还是本身,所以要先减去本身
	ans -= num[sum[x]^k];
}

int main()
{
#ifdef zsc
	freopen("input.txt","r",stdin);
#endif

	int n,m,i,j;
	while(~scanf("%d%d%d",&n,&m,&k))
	{
		memset(num,0,sizeof(num));
		sz = sqrt(n*1.0);
		sum[0] = 0;
		for(i=1;i<=n;++i){
			scanf("%d",&sum[i]);
			sum[i]^=sum[i-1];
		}
		for(i=1;i<=m;++i){
			scanf("%d%d",&a[i].L,&a[i].R);
			a[i].id = i;
		}
		sort(a+1,a+m+1,cmp);
		int L=1,R=0;//L之所以为1是因为要在[L-1,R+1]区间才有可能L<=R+1
		ans = 0;
		for(i=1;i<=m;++i){
			//收缩到[L-1,R]区间
			while(R<a[i].R)add(++R);
			while(R>a[i].R)sub(R--);
			while(L>a[i].L-1)add(--L);
			while(L<a[i].L-1)sub(L++);
			Ans[a[i].id] = ans; 
		}
		for(i=1;i<=m;++i){
			printf("%I64d\n",Ans[i]);
		}
	}

	return 0;
}


你可能感兴趣的:(莫队算法)