Atcoder D - Xor Sum 2 (异或和和数值和的关系)

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≤lrN) 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 XOR

Constraints

  • 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≤lrN) 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 Axor 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

异或和与数值和的关系>>>(a+b)>=a^b
两者相等的情况当且仅当当前的所有的二进制数位上的1仅出现过一次>>
运用双指针的算法>>即可解决>>因为假如当前已经不满足相等的条件了>>那么在l之前所有的左坐标与右坐标显然已经不满足
所以放心使用双指针>>
666啊

 
  
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+10;ll sum[N],X[N];
ll a[N];
int main(){
    int n;scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
    sum[1]=X[1]=a[1];
    for(int i=2;i<=n;i++) sum[i]=sum[i-1]+a[i],X[i]=X[i-1]^a[i];
    ll ans=0;int l=1;
    for(int r=1;r<=n;r++){
        for(;sum[r]-sum[l-1]!=(X[r]^X[l-1]);l++);
        ans+=(r-l+1);
    }
    printf("%lld\n",ans);
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/vainglory/p/9231226.html