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
Copy
4 2 5 4 6
Sample Output 1
Copy
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
Copy
9 0 0 0 0 0 0 0 0 0
Sample Output 2
Copy
45
Sample Input 3
Copy
19 885 8 1 128 83 32 256 206 639 16 4 128 689 32 8 64 885 969 1
Sample Output 3
Copy
37
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstdlib> 5 #include <cstring> 6 #include <string> 7 #include <deque> 8 using namespace std; 9 #define ll long long 10 #define N 200009 11 #define gep(i,a,b) for(int i=a;i<=b;i++) 12 #define gepp(i,a,b) for(int i=a;i>=b;i--) 13 #define gep1(i,a,b) for(ll i=a;i<=b;i++) 14 #define gepp1(i,a,b) for(ll i=a;i>=b;i--) 15 #define mem(a,b) memset(a,b,sizeof(a)) 16 int n,a[N]; 17 ll sum[N],b[N]; 18 /* 19 要想相加和等于异或和,就要区间的数二进制的每一位1只有一个 20 例如 1 2 4 8 21 如果 [l,r] 不可以,那么l++ 22 如果[l,r] 可以,那么 r++ 23 */ 24 int main() 25 { 26 scanf("%d",&n); 27 gep(i,1,n) { 28 scanf("%d",&a[i]); 29 sum[i]=sum[i-1]+a[i]; 30 b[i]=b[i-1]^a[i]; 31 } 32 int l=1; 33 ll ans=0; 34 gep(r,1,n){ 35 for(;sum[r]-sum[l-1]!=(b[r]^b[l-1]);l++);//!=的优先级大于^,因此要加() 36 ans+=(r-l+1); 37 //[l,r] :每一次的可以就是多了[l,r],[l+1,r],[l+2,r]……[r,r]共(r-l+1)个区间 38 //可以一定是连续的,一旦不可以了就要改变r,l 39 } 40 printf("%lld ",ans); 41 return 0; 42 }