845--1777F - Comfortably Numb
思路
单调栈预处理区间,然后对短的一边进行枚举,对长度一边匹配。
代码
#include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 5;
void Up_Stk(int n, int a[], int l[], int r[]) {
for(int i = 1; i <= n; i++) {
int j = i;
while(j > 1 && a[j - 1] <= a[i])j = l[j -1];
l[i] = j;
}
for(int i = n; i; i--) {
int j = i;
while(j < n && a[j + 1] < a[i])j = r[j + 1];
r[i] = j;
}
}
struct Lasting_01tire {
const int N = 30;
struct node {
int ch[2], cnt;
}tr[M * 32];
int rot[M], tot;
void insert(int pre, int &now, int i, int x) {
tr[now = ++tot] = tr[pre];
tr[now].cnt++;
if(i < 0)return ;
int v = x >> i & 1;
tr[now].ch[v ^ 1] = tr[pre].ch[v ^ 1];
insert(tr[pre].ch[v], tr[now].ch[v], i - 1, x);
}
int query(int l, int r, int x) {//直接传入你需要匹配的范围就可以了
l = l > 1 ? rot[l - 2] : 0;
r = rot[r];
int ans = 0;
for(int i = N; i >= 0; i--) {
int v = x >> i & 1;
if(tr[tr[r].ch[v ^ 1]].cnt - tr[tr[l].ch[v ^ 1]].cnt) {
ans += 1 << i;
l = tr[l].ch[v ^ 1];
r = tr[r].ch[v ^ 1];
}
else {
l = tr[l].ch[v];
r = tr[r].ch[v];
}
}
return ans;
}
void reset(int n) {
for(int i = 0; i <= n + 1; i++)rot[i] = 0;
for(int i = 0; i <= tot; i++)
tr[i].ch[0] = tr[i].ch[1] = tr[i].cnt = 0;
tot = 0;
}
void build(int n, int sum[]) {//这里是已经前缀和过的数组
reset(n);
insert(0, rot[0], N, 0);
for(int i = 1; i <= n; i++)
insert(rot[i - 1], rot[i], N, sum[i]);
}
}Tr;
int a[M], sum[M], l[M], r[M];
int f(int now, int l, int r) {
int ans = 0;
if(r - now > now - l) {//固定左边,匹配右边
for(int i = l; i <= now; i++)
ans = max(ans, Tr.query(now + 1, r, sum[i - 1] ^ a[now]));
}
else {//固定右边,匹配左边
for(int i = now; i <= r; i++)
ans = max(ans, Tr.query(l, now - 1, sum[i] ^ a[now]));
}
return ans;
}
void solve() {
int n; cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i];
sum[i] = sum[i - 1] ^ a[i];
}
Up_Stk(n, a, l, r);
Tr.build(n, sum);
int ans = 0;
for(int i = 1; i <= n; i++)
ans = max(ans, f(i, l[i], r[i]));
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int TT; cin >> TT;
while(TT--) {
solve();
}
return 0;
}

浙公网安备 33010602011771号