cf div2 340 E. XOR and Favorite Number(莫队算法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Timeclimber/article/details/81286232

E. XOR and Favorite Number

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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 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.

Output

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

Examples

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

Note

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.

题意:

给了一个长度为N的序列和M次询问,每次询问a[l]...a[r]有多少个满足1<=i<=j<=n使得a[l]^...^a[r]为k。

思路:

考虑到异或的一个性质,a[1]^....^a[l-1]^a[1]^...^a[r]=a[l]^...a[r]。

所以可以先处理出一个异或的前缀和。

接下来问题变成了:

a[l-1]^a[r]=k,满足这个的l和r有多少个。

两边同异或一个值,

a[l-1]=k^a[r] 或 a[r]=k^a[l-1]

然后用莫队处理一下就好了。

注意:

1.在添加和删除时,对前缀和的记录的值,不应该影响原来的答案。

2.l在移动的时候,注意移动后l-1的值要存在或消失。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=2e6;
typedef long long ll;
int a[maxn];//异或的前缀和
int pos[maxn];
ll sum[maxn];
ll res[maxn];
ll ans;
int n,m,k;
struct node
{
    int l,r,id;
}q[maxn];
bool cmp(node a,node b)
{
    if(pos[a.l]==pos[b.l])
        return a.r<b.r;
    return pos[a.l]<pos[b.l];
}
void add(int x)
{
    ans+=sum[a[x]^k];//加的另一端点前缀和的次数
    sum[a[x]]++;//加的x端点前缀和出现次数
}
void del(int x)
{
    sum[a[x]]--;//与add的顺序相反才能把这点对答案的贡献移除,对结果不影响
    ans-=sum[a[x]^k];
}
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    int sz=sqrt(n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        a[i]=a[i]^a[i-1];
        pos[i]=i/sz;
    }
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&q[i].l,&q[i].r);
        q[i].id=i;
    }
    sort(q+1,q+1+m,cmp);
    int l=1,r=0;
    sum[0]=1;
    for(int i=1;i<=m;i++)
    {
        while(l<q[i].l) del(l-1),l++;
        while(l>q[i].l) l--,add(l-1);
        while(r<q[i].r) r++,add(r);
        while(r>q[i].r) del(r),r--;
        res[q[i].id]=ans;
    }
    for(int i=1;i<=m;i++)
        cout<<res[i]<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Timeclimber/article/details/81286232
今日推荐