设 表示考虑前 个位置最多能形成多少个异或和为 的区间。
转移分两种情况讨论:
- 不属于任何区间,此时 。
- 是最后一个区间的右端点,枚举该区间左端点 ,此时 。
区间异或可以用前缀异或和求。时间复杂度 。
注意到对任意 ,都有 。因此在转移 2 中,只需找到最靠右的位置 使得 ,用 转移即可。
由 得 。用 记录当前最后一次出现 的位置 ,直接查询 即可。时间复杂度 。
AC Code
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 5;
int a[MAXN], s[MAXN];
int las[11000000];
int dp[MAXN];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; ++i){
cin >> a[i];
s[i] = s[i - 1] ^ a[i];
}
memset(las, -1, sizeof(las));
las[0] = 0;
for (int i = 1; i <= n; ++i) {
f[i] = f[i - 1]; // 转移 1
int need = s[i] ^ k;
if (las[need] != -1) {
f[i] = max(f[i], f[las[need]] + 1);
} // 转移 2
las[s[i - 1]] = i;
}
cout << f[n] << "\n";
}