题意:给定一个长度为 n 的序列,尝试选择尽可能多的不相交的区间,使每个区间的异或和都为 。
思路:
问题可以转化成
我们要选择一系列下标 ,使得:
所以,维护一个哈希表(map 和 set 均可),从左到右扫过去,每次看看是否存在对应的端点。如果是,记录答案,清空哈希表。
注意:对于 这个端点需要特殊记录。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 5e5 + 7;
int n,k;
// x ^ y = k -> x = y ^ k
set<int>st; // O(log n)
int a[N],pre_xor[N];
int ans = 0;
signed main(){
//freopen("xor.in","r",stdin);
//freopen("xor.out","w",stdout);
scanf("%d%d",&n,&k);
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
pre_xor[1] = a[1];
st.insert(0);
for(int i = 2;i <= n;i++) pre_xor[i] = pre_xor[i-1] ^ a[i];
for(int j = 1;j <= n;j++){
if(st.find(pre_xor[j] ^ k) != st.end()){
// pre_xor[j] ^ k -> pre_xor[i]
++ans;
st.clear();
}
st.insert(pre_xor[j]);
}
printf("%d\n",ans);
return 0;
}
后记:祝愿考生们如鱼得水,心想事成!
被年龄制裁了!!!