D - Xor Sum 2
Time limit : 2sec / Memory limit : 1024MB
Score : 500 points
Problem Statement
There is an integer sequence A of length N.
Find the number of the pairs of integers l and r (1≤l≤r≤N) that satisfy the following condition:
- Al xor Al+1 xor … xor Ar=Al + Al+1 + … + Ar
Here, xor denotes the bitwise exclusive OR.
Definition of XORConstraints
- 1≤N≤2×105
- 0≤Ai<220
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A1 A2 … AN
Output
Print the number of the pairs of integers l and r (1≤l≤r≤N) that satisfy the condition.
Sample Input 1
4 2 5 4 6
Sample Output 1
5
(l,r)=(1,1),(2,2),(3,3),(4,4) clearly satisfy the condition. (l,r)=(1,2) also satisfies the condition, since A1 xor A2=A1 + A2=7. There are no other pairs that satisfy the condition, so the answer is 5.
Sample Input 2
9 0 0 0 0 0 0 0 0 0
Sample Output 2
45
Sample Input 3
19 885 8 1 128 83 32 256 206 639 16 4 128 689 32 8 64 885 969 1
Sample Output 3
37
BUG反馈门
因此在区间[1,3]任意连续区间都是满足原始连续异或等于连续和的关系式;
双指针移动,确定当前的l,看当前的r所能到达的最右边的位置
由于在区间[l,r]内都是满足条件的....在l不断向右移动的过程中,[l,r]的和能和a[r]&之后也是满足条件的
移动过程中 必定得满足r>=l+1
因此时间复杂度为2*n
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2e5+7;
int a[maxn];
int main (){
int n;scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
int r=1,i=0;
ll now=a[0],ans=0;
while(i<n){
if(r<n&&(now&a[r])==0){
now+=a[r];
r++;
}
else {
now-=a[i];
ans+=r-i;
i++;
if(i>=r) {
r=i+1;
now=a[i];
}
}
}
printf("%lld\n",ans);
return 0;
}