0%

后缀自动机SAM板子

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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int aqx=1,byx=1,inf=0x3f3f3f3f;
const int mod=998244353;
const int N=1e6+5;
class SAM{public:
int tot,lst;
struct nod{
int ch[26],fail,len;
}t[N*2];
int sz[N*2]; // sz[u]=1表示u在主链上;求fail树子树和则为u的出现次数
vector<int>g[N];
inline void extend(int c){
int p=lst,np=lst=++tot;
sz[np]=1,t[np].len=t[p].len+1;
for(;p&&!t[p].ch[c];p=t[p].fail)t[p].ch[c]=np;
if(!p){t[np].fail=1;return;}
int q=t[p].ch[c];
if(t[q].len==t[p].len+1){t[np].fail=q;return;}
int nq=++tot;
t[nq]=t[q],t[nq].len=t[p].len+1,t[q].fail=t[np].fail=nq;
for(;p&&t[p].ch[c]==q;p=t[p].fail)t[p].ch[c]=nq;
}
inline void build(string s){
tot=lst=1;
for(char ch:s)extend(ch-'a');
}
inline ll work(){
// fail边一定是len大的连向len小的
for(int i=2;i<=tot;i++)g[t[i].len].push_back(i);
for(int i=t[lst].len;i;i--)
for(int j:g[i])sz[t[j].fail]+=sz[j];
ll ret=0;
for(int i=2;i<=tot;i++)if(sz[i]>1)ret=max(ret,(ll)sz[i]*t[i].len);
return ret;
}
}a;
void solve(){
string s;cin>>s;
a.build(s);
ll ans=a.work();
cout<<ans<<'\n';
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0);
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
for(;byx<=aqx;byx++)solve();
return 0;
}
------ Q.E.D.~~~喵~~~ ------