AtCoder Regular Contest 098-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 (1lrN) 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

  • 1N2×105
  • 0Ai<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 (1lrN) 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

题意:找出所有的l和r

在1到n里找出所有任意长度的(r-l)共有1+2+.....+n-1种不同情况,n每增加一,那么它都会比n没有增加前,多出n-1种可能。所以可以通过这个规律加起所有情况,本问题的解决用了尺取法的思想。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

long long sum[200010],xo[200010];
int main()
{
    ios::sync_with_stdio(false);
    int N,a;
    cin>>N;
    for(int i=1;i<=N;i++){
        cin>>a;
        xo[i]=xo[i-1]^a;
        sum[i]=sum[i-1]+a;
    }
    int l=0;
    long long ans=0;
    for(int i=1;i<=N;i++){
        while(sum[i]-sum[l]!=(xo[i]^xo[l])){
            l++;
        }
        ans=ans+i-l;//记录每一次变化多出的组合数目
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_40948489/article/details/80465726