题意:找出一段最长的子串分成三部分abc,其中ab为回文串,ac相等(可得bc也是回文串)
这里将分割abc的两个点分别看成第一分割点x和第二分割点y,那么用manacher求出每个点为中心的最长分割点之后,对于第一ab这个回文串,可以知道的是它的长度为偶数,第一分割点为其中间的那个位置,再来看第二分割点的位置,由manecher的性质知道,假如有这么一段子串(abcd随便表示数字,并不一定相同)aaaaaaa(x)bbbbbbbb(y)cccccccc dddddddddd,那么对于第一分割点来说,第二分割点只可能在c这些位置里面,因为超过c最右位置,以x为中心的回文串不能延伸到了。所以对于x,只需找到c里面最靠右的y点,使得以y为中心的回文串的最左位置在x前面即可,那么就可以用线段树维护这个值。然后再对每一个字符都扫一遍得到答案即可,复杂的nlogn。注意线段树build的初始化,val为pos这个位置向左延伸的最左位置
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL INF = (1LL << 60);
const int inf = 0x3f3f3f3f;
const int N = 200010;
struct SegTree {
int l, r;
int val;
int pos;
}tree[N << 2];
int p[N << 1];
int buf[N];
int str[N << 1];
void manacher(int cnt) {
memset(p, 0, sizeof(p));
int MaxId = 0, id;
for (int i = 2; i < cnt; ++i) {
if (MaxId > i) {
p[i] = min(p[2 * id - i], MaxId - i);
}
else {
p[i] = 1;
}
while (str[i + p[i]] == str[i - p[i]]) {
++p[i];
}
if (p[i] + i > MaxId) {
MaxId = p[i] + i;
id = i;
}
}
}
void build(int p, int l, int r) {
tree[p].l = l;
tree[p].r = r;
tree[p].pos = -inf;
tree[p].val = inf;
if (l == r) {
tree[p].pos = l;
return;
}
int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
}
void pushup(int p) {
if (tree[p << 1].val < tree[p << 1 | 1].val) {
tree[p].val = tree[p << 1].val;
tree[p].pos = tree[p << 1].pos;
}
else if (tree[p << 1].val >= tree[p << 1 | 1].val) {
tree[p].val = tree[p << 1 | 1].val;
tree[p].pos = tree[p << 1 | 1].pos;
}
}
void update(int p, int pos, int val) {
if (tree[p].l == tree[p].r) {
tree[p].val = val;
return;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (pos <= mid) {
update(p << 1, pos, val);
}
else {
update(p << 1 | 1, pos, val);
}
pushup(p);
}
int pos;
int val;
void query(int p, int l, int r) {
if (l <= tree[p].l && tree[p].r <= r) {
if (tree[p].val <= val) {
pos = max(tree[p].pos, pos);
}
return;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (r <= mid) {
query(p << 1, l, r);
}
else if (l > mid) {
query(p << 1 | 1, l, r);
}
else {
query(p << 1, l, mid);
query(p << 1 | 1, mid + 1, r);
}
}
int main() {
int t, icase = 1;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &buf[i]);
}
int cnt = 3;
str[1] = -1;
str[2] = -2;
for (int i = 1; i <= n; ++i) {
str[cnt++] = buf[i];
str[cnt++] = -2;
}
str[cnt] = -3;
manacher(cnt);
build(1, 1, n);
int now = 0;
for (int i = 4; i < cnt; i += 2) {
++now;
if (p[i] - 1 <= 0) {
continue;
}
update(1, now, now - (p[i] - 1) / 2 + 1);
}
int ans = 0;
now = 0;
for (int i = 4; i < cnt; i += 2) {
++now;
if (p[i] - 1 <= 0) {
continue;
}
//第一个分割点位置是now之后, now+1之前
val = now + 1; // 应该<= now+1
pos = -1;
int R = now + (p[i] - 1) / 2 - 1;
R = min(R + 1, n);
if (now + 1 <= R) {
//printf("位置%d, 区间[%d, %d]\n", now, now + 1, R);
query(1, now + 1, R);
if (pos != -1) {
ans = max(ans, pos - now);
}
}
}
printf("Case #%d: %d\n", icase++, ans * 3);
}
return 0;
}