Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4287 [SHOI2011]双倍回文

P4287 [SHOI2011]双倍回文

注意到满足条件的串是一个回文串,其前一半和后一半也是回文串,建出回文树后,对于一个点,找到祖先中一个 $len _ i = 2 len _ p$ 的点那么就是合法的。显然的办法是倍增可以做到 $O(n \log n)$ 。记 $f _ i$ 位置 $i$ 祖先上能和字符 $i$ 构成回文串并且 $len \le \frac {len _ i} 2$ 的点,考虑从来边的 $f$ 转移,只需要跳常数次父亲即可得到 $f _ i$ 。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdio>
#include <algorithm>
using namespace std;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0';
flag && (x = ~x + 1);
}
template <class Type, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write (Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar('0' + x % 10);
}
const int N = 5e5 + 10;
char str[N];
int n, cnt, last, f[N];
struct Node { int p, len, nxt[26]; } tr[N];
int get (int x, int t)
{
while (str[t - 1 - tr[x].len] != str[t]) x = tr[x].p;
return x;
}
int main ()
{
read(n);
scanf("%s", str + 1), str[0] = '$';
tr[0].p = 1, tr[1].len = -1;
last = 0, cnt = 2;
for (int i = 1; i <= n; ++i)
{
int c = str[i] - 'a', p = get(last, i);
if (!tr[p].nxt[c])
{
int q = cnt++;
tr[q].len = tr[p].len + 2;
tr[q].p = tr[get(tr[p].p, i)].nxt[c];
tr[p].nxt[c] = q;
if (tr[q].len <= 2) f[q] = tr[q].p;
else
{
int t = f[p];
while (str[i - 1 - tr[t].len] != str[i] || (tr[t].len + 2) * 2 > tr[q].len) t = tr[t].p;
f[q] = tr[t].nxt[c];
}
}
last = tr[p].nxt[c];
}
int res = 0;
for (int i = 2; i < cnt; ++i)
if (tr[f[i]].len * 2 == tr[i].len && tr[i].len % 4 == 0)
res = max(res, tr[i].len);
write(res);
return 0;
}