Educational Codeforces Round 12-E. Beautiful Subarrays

维护一个异或的前缀数组sum(),并把数组中的数挂在字典树上,寻找在sum(0)..sum(i-1)中和sum(i)异或值大于等于K的数的数目.累加

#include <bits/stdc++.h>
#define maxn 205
#define INF 1e9
using namespace std;
typedef long long ll;
typedef struct Node{
    int num;
    Node *p[2];
}*T;
T root;
int sum[1000006], k;
T NewNode(){

    T p = (T)malloc(sizeof(Node));
    memset(p, 0, sizeof(Node));
    return p;
}
void Insert(int n){

    T m = root;
    for(int i = 29; i >= 0; i--){

        int s = (n >> i) & 1;
        if(m -> p[s] == 0){ 
          m -> p[s] = NewNode();
        }
        m = m -> p[s];
        m -> num++;
    }   
}
int Query(int n){

    T m = root;
    int cnt = 0, i;
    for(i = 29; i >= 0; i--){

        int s1 = (n >> i) & 1, s2 = (k >> i) & 1;
        int s = s1 ^ s2;
        if(s2 == 0){
            if(m -> p[s^1]){
                cnt += m -> p[s^1] -> num;
            }
        }
        if(m -> p[s])
         m = m -> p[s];
        else
         break;
    }
    if(i == -1)
      cnt += m -> num;
    return cnt;
}
void Destory(T t){

    if(t -> p[0])
     Destory(t -> p[0]);
    if(t -> p[1])
     Destory(t -> p[1]);
    free(t);
}
int main(){

// freopen("in.txt", "r", stdin);

    int n;
    while(cin >> n >> k){

        root = NewNode();
        ll cnt = 0;
        Insert(0);
        for(int i = 1; i <= n; i++){
            scanf("%d", sum+i);
            sum[i] ^= sum[i-1];
            cnt += Query(sum[i]);
            Insert(sum[i]);
        }
        Destory(root);
        cout << cnt << endl;
    }
    return 0;
}

你可能感兴趣的:(Educational Codeforces Round 12-E. Beautiful Subarrays)