cf round340 div2 F(莫隊)

題目鏈接:傳送門


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

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



題目大意:


給你一個序列a,和m次詢問,和一個數k,每次詢問你一個區間[l,r],問你在這個區間中有多少對i,j使得區間[i,j]的異或和等於k


題目思路:


首先考慮區間異或和,我們可用個數組pre[i] 表示前i個數的異或和,通過異或的性質我們可以求出i,j的異或和爲pre[j]^pre[i-1]

有了這個我們還可以用個數組flag[i]表示當前這個 數i出現的次數,有了這些,如果我們知道了[i,j]的答案,那麼我們可以在

O(1)的時間內求出[i-1][j],[i+1][j],[i][j-1],[i][j+1]內的值,所以有了這個我們就很好想到莫隊,莫隊的複雜度爲m*sqrt(n)

關於莫隊可以看這個博客:莫隊詳解

首先我們將區間分塊,然後按快排序,然後對於我知道區間[L,R]的答案來求查詢區間[l,r]的答案,這裏可以做到

總複雜度爲m*sqrt(n)


AC代碼:


#include<bits/stdc++.h>
using namespace std;
const int maxn = 1<<20;
struct node
{
    int l,r,id;
}q[maxn];
int a[maxn],pos[maxn];
int n,m,k,L=1,R=0;
long long Ans=0,flag[maxn],ans[maxn];
bool cmp(node a,node b)
{
    if(pos[a.l]==pos[b.l])
        return a.r<b.r;
    else return pos[a.l]<pos[b.l];
}
void add(int x)
{

    Ans+=flag[a[x]^k];
    flag[a[x]]++;
}
void del(int x)
{
    flag[a[x]]--;
    Ans-=flag[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);
    flag[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--;
        }
        ans[q[i].id] = Ans;
    }
    for(int i=1;i<=m;i++)
        cout<<ans[i]<<endl;

    return 0;
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章