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

Topic links: http://codeforces.com/contest/617/problem/E

Title effect: The number n and m have queries, each query interval [l, r] Q satisfies ai ^ ai + 1 ^ ... ^ aj == k of the (i, j) (l <= i <= j <= r) number of pairs.

Problem-solving ideas: a first pre-out prefix and XOR array sum array, a [l] ^ a [l + 1] ^ a [l + 2] ...... ^ a [r] is equal to sum [r] ^ sum [l-1]

Then we use the algorithm Mo team record prefix and the number of occurrences of the array with an array cnt

We are looking for a prefixed number of exclusive OR with the current prefix and an exclusive OR value of k, the corresponding array cnt to find a [i] ^ number k and update the answers on the line before.

Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1<<20;
ll pos[maxn],flag[maxn],ans[maxn];
int a[maxn];
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];
}
int n,m,k;
int L=1,R=0;
ll Ans=0;
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-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;
    }
    flag[0]=1;
    sort(Q+1,Q+m+1,cmp);
    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++)
    printf("%I64d\n",ans[i]);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/zjl192628928/p/11260537.html