题解:P13895 [蓝桥杯 2023 省 C] 异或和之差
Description
给定非负整数序列
Solution
为了保证子段不相交,我们可以枚举断点,让两段子段在断点两边。
那么如果我们能求出
考虑怎么维护 01 Trie 中,贪心求出最大或最小值即可。
时间复杂度
代码实现细节较多。参考:
Code
#include <bits/stdc++.h>
#define fi first
#define se second
#define inf 1e9
using namespace std;
using ll = long long;
using db = double;
using pii = pair<int, int>;
constexpr int N = 2e5 + 5, M = 21, P = 1e9 + 7;
int n, a[N];
struct Trie {
int trie[N * M][2], cnt;
void insert(int x) {
int p = 0;
for (int i = 20; ~i; -- i) {
bool t = (x >> i) & 1;
if (!trie[p][t]) trie[p][t] = ++ cnt;
p = trie[p][t];
}
return;
}
int max(int x) {
int res = 0, p = 0;
for (int i = 20; ~i; -- i) {
bool t = (x >> i) & 1;
if (trie[p][!t]) res |= 1 << i, p = trie[p][!t];
else p = trie[p][t];
}
return res;
}
int min(int x) {
int res = 0, p = 0;
for (int i = 20; ~i; -- i) {
bool t = (x >> i) & 1;
if (trie[p][t]) p = trie[p][t];
else res |= 1 << i, p = trie[p][!t];
}
return res;
}
void clear() {return memset(trie, 0, sizeof trie), cnt = 0, insert(0);}
} trie;
int pre[N], ans;
int main() {
cin.tie(nullptr) -> sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; ++ i) cin >> a[i];
trie.clear();
for (int i = 1, sum = 0; i < n; ++ i) {
pre[i] = max(pre[i - 1], trie.max(sum ^ a[i]));
trie.insert(sum ^= a[i]);
}
trie.clear();
for (int i = n, sum = 0; i > 1; -- i) {
ans = max(ans, abs(pre[i - 1] - trie.min(sum ^ a[i])));
trie.insert(sum ^= a[i]);
}
trie.clear();
for (int i = 1, sum = 0; i < n; ++ i) {
pre[i] = max(pre[i - 1], trie.min(sum ^ a[i]));
trie.insert(sum ^= a[i]);
}
trie.clear();
for (int i = n, sum = 0; i > 1; -- i) {
ans = max(ans, abs(trie.max(sum ^ a[i]) - pre[i - 1]));
trie.insert(sum ^= a[i]);
}
cout << ans << '\n';
return 0;
}