循环同构串的判断+broder剃头截尾法实现均摊:P3546

本文搬运自本人高中时期CSDN博客,若图片加载不出来,可到原文查看:https://blog.csdn.net/zhangtingxiqwq/article/details/135126979

https://www.luogu.com.cn/problem/P3546

两个串的循环同构可以表示成: ABBA ,所以我们等价于在原串求:

在这里插入图片描述

显然A可以枚举,我们现在就是要求原串所有中心串的最长不交broder。

这个方法之前提到过,我们可以用broder剃头截尾法。

fif_i 表示 AA 的长度为 ii ,显然有 fifi+1+2f_i\le f_{i+1}+2 ,我们暴力缩小 ff ,复杂度显然可以均摊

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
#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) fprintf(stdout, ##__VA_ARGS__)
#else
#define debug(...) void(0)
#endif
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define Z(x) (x)*(x)
#define pb push_back
#define fi first
#define se second
//#define M
#define mo 998244353
#define N 1000010
void Mod(int &a) { a%=mo; a+=mo; a%=mo; }
int n, m, i, j, k, T, f[N], c[N], fac[N], ans;
int l, r;
char str[N];

int substr(int a, int b) {
return ((c[b]-c[a-1]*fac[b-a+1])%mo+mo)%mo;
}

bool cmp(int a, int b, int c, int d) {
return substr(a, b) == substr(c, d);
}

signed main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// srand(time(NULL));
// T=read();
// while(T--) {
//
// }
n=read(); scanf("%s", str+1); ans=0;
for(i=fac[0]=1; i<=n; ++i)
c[i]=c[i-1]*29+str[i]-'a'+1, Mod(c[i]),
fac[i]=fac[i-1]*29%mo;
for(i=n/2; i>=1; --i) {
l=i; r=n-i+1;
f[i]=f[i+1]+2;
while(f[i] && (l+f[i]-1>=r-f[i]+1 || !cmp(l, l+f[i]-1, r-f[i]+1, r)))
--f[i];
debug("f[%lld][%lld : %lld] = %lld \n", i, l, r, f[i]);
}
for(i=1; i<=n/2; ++i)
if(cmp(1, i, n-i+1, n)) {
debug("%d is ok !\n", i);
ans=max(ans, i+f[i+1]);
}
printf("%lld", ans);
return 0;
}