CodeForces - 617E XOR and Favorite Number (莫隊+前綴和)
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, a
Input
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.
Output
Print m lines, answer the queries in the order they appear in the input.
Examples
Input6 2 3Output
1 2 1 1 0 3
1 6
3 5
7Input
0
5 3 1Output
1 1 1 1 1
1 5
2 4
1 3
9
4
4
題意:
詢問區間內異或和剛好為k的字段個數。
思路:
莫隊+前綴和。
這個前綴和比較套路,用的是前綴異或和。
字段【l,r】的異或和就是pre[r]^pre[l-1],
這種情況下我們在莫隊的過程中記錄l,r的pre[i]出現的次數,就可以完成更新了。
註意當L<q[i].l時,要先讓記錄per[L]出現次數的個數減一。
#include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<map> #include<set> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #define fuck(x) cout<<#x<<" = "<<x<<endl; #define debug(a,i) cout<<#a<<"["<<i<<"] = "<<a[i]<<endl; #define ls (t<<1) #define rs ((t<<1)+1) using namespace std; typedef long long ll; typedef unsigned long long ull; const int maxn = 100086; const int maxm = 1000086; const int inf = 2.1e9; const ll Inf = 999999999999999999; const int mod = 1000000007; const double eps = 1e-6; const double pi = acos(-1); int num[maxm*2],pre[maxn],a[maxn]; struct node{ int l,r; int id; }q[maxn]; ll ans[maxn]; ll anss; int block; bool cmp(node a,node b){ if(a.l/block!=b.l/block){return a.l<b.l;} return a.r<b.r; } int main() { int n,m,k; scanf("%d%d%d",&n,&m,&k); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); pre[i]=pre[i-1]^a[i]; } block=sqrt(n); 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; anss=0; num[0]=1; for(int i=1;i<=m;i++){ while(L<q[i].l){ int t=k^pre[L-1]; num[pre[L-1]]--;///註意語句順序 anss-=num[t]; L++; } while(R>q[i].r){ int t=k^pre[R]; num[pre[R]]--; anss-=num[t]; R--; } while(L>q[i].l){ L--; int t=k^pre[L-1]; anss+=num[t]; num[pre[L-1]]++; } while(R<q[i].r){ R++; int t=k^pre[R]; anss+=num[t]; num[pre[R]]++; } ans[q[i].id]=anss; } for(int i=1;i<=m;i++){ printf("%lld\n",ans[i]); } return 0; }View Code
CodeForces - 617E XOR and Favorite Number (莫隊+前綴和)