这里给出一个场上能过大样例的神秘map套vector的邪教做法
首先我们考虑一种的枚举所有可能的区间的做法,为了省掉每次区间扫描的 的开销,可以使用异或前缀和即 ,时间复杂度
可以通过以下方式实现
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
if (s[j] ^ s[i - 1] == k) {
...
}
}
}但是这样有一个问题,我们只知道所有符合条件的区间,但是怎么选才可以最多呢?
这里显然可以贪心求解,将所有可行区间按右端点排序,优先选右端点靠右的然后统计答案即可
时间复杂度
但是有因为 , 的时间复杂度肯定会超时所以考虑优化
注意到为了选择的答案尽可能的大,当对于一个 有多个 使 时 越靠前越优,所以可以找到就 掉
但是这样时间复杂度还是没有得到根本上的优化,那么如何快速找到符合条件的 满足 且 呢?
由于符合条件的 一定是单调递增的所以可以考虑记录所有可能 然后二分求解
时间复杂度
于是就有这篇屎山代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<typename T> inline T read(T &x) { x = 0; T f = 1; char ch = cin.get(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = cin.get(); } while (isdigit(ch)) { x = (x << 1ll) + (x << 3ll) + (ch ^ 48); ch = cin.get(); } return x * f; }
template<typename T> inline void write(T x) { if (x < 0) { cout.put('-'); x = -x; } if (x > 9) write(x / 10); cout.put(x % 10 + '0'); }
struct node {
ll l, r;
};
ll n, k, c;
ll ans, lst;
ll a[500005], s[500005];
node qj[500005];
unordered_map<ll, vector<ll> > mp;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i];
s[i] = s[i - 1] ^ a[i];
mp[s[i]].push_back(i);
}
for (int i = 1; i <= n; i++) {
ll t = s[i - 1] ^ k;
if (mp[t].empty()) continue;
ll p = lower_bound(mp[t].begin(), mp[t].end(), i) - mp[t].begin();
if (p == mp[t].size()) continue;
if (mp[t][p] != 1e18 && mp[t][p] >= i) {
qj[++c] = {i, mp[t][p]};
}
}
sort(qj + 1, qj + 1 + c, [](node a, node b) {
return a.r < b.r;
});
lst = -1e18, ans = 0;
for (int i = 1; i <= c; i++) {
if (lst < qj[i].l) {
ans++, lst = qj[i].r;
}
}
cout << ans << endl;
return 0;
}