AtCoder Regular Contest 098 D - Xor Sum 2 区间异或=相加 DP思想

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

题意:给出n个数,求它的连续子序列中,满足下列公式,(l,r)的对数有多少对

Al xor Al+1 xor … xor Ar=Al Al+1 + … Ar

思路:由题意可以得到,连续子序列,如果在ai这个数不符合公式的话,即之后的符合条件的对数中将不在需要这个元素,所有枚举元素来计算符合公式的对数 。

难以理解的就是异或等效于加法与减法(!!!)

#include
using namespace std;
const int maxn = 200005;
long long f[maxn], s[maxn];
long long ans;

int main(){
    int n, x; cin >> n;
    for(int i = 1; i <= n; i++){
        scanf("%d", &x);
        f[i] = f[i-1] + x;    //计算异或前缀和
        s[i] = s[i-1] ^ x;    //计算加法前缀和
    }
    int l = 1;
    ans=0;
    for(int r = 1; r <= n; r++){         //枚举元素
        for(; f[r] - f[l-1] != (s[r] ^ s[l-1]); l++);//如果符合条件的话 则立即退出进行计算
        ans += r - l + 1;
    }
    printf("%lld\n", ans);
    return 0;
}

今天这场Atcoder感觉就是区间+DP的思想

你可能感兴趣的:(ACM_经典DP,ACM_区间DP,弱项—区间问题)