codeforce 1113C Sasha and a Bit of Relax (異或規律)

https://codeforces.com/contest/1113/problem/C

題意

給一段序列,求出滿足下列條件的區間的個數。

  1. [L,R]長度爲偶數
  2. aLaL+1aL+2amid=amid+1amid+2aRa_L ⊕ a_{L+1}⊕a_{L+2} \dots⊕a_{mid} =a_{mid+1}⊕a_{mid+2}⊕\dots⊕a_R

題解

如果a⊕b=c⊕d,那麼(a⊕b)⊕(c⊕d)=0,即只有相等的值異或才爲0。
異或也有前綴異或,[L,R]的異或值爲preRpreL1pre_{R}⊕pre_{L-1}
問題轉化爲preRpreL1=0pre_{R}⊕pre_{L-1}=0,即preR=preL1pre_{R}=pre_{L-1}
所以可以在計算前綴積的時候就統計出preipre_{i}出現的次數,只要兩個相等的值就可以組成一個符合條件的區間,因爲區間長度要是偶數,所以可以分奇偶來統計。

代碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 3e5+5;
const int mod = 1e9+7;

int a[maxn],pre[maxn];
map<int,int> cnt[2];
int main() {
    int n;
    scanf("%d", &n);
    cnt[0][0] = 1;
    int sum=0;
    long long ans = 0;
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &a[i]);
        sum^=a[i];
        ans += cnt[i%2][sum];
        cnt[i%2][sum]++;
    }
    cout << ans << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章