多个串求lcs,
每次匹配,每个节点记录该节点匹配的最长串。然后每个节点需要根据拓扑序更新到pre[x]上。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 2*2.5e5 + 8;
int sum[maxn],temp[maxn];
string s;
struct SAM{
int ch[maxn][26], pre[maxn], val[maxn];
int last, tot, minl[maxn], maxl[maxn];
void init(){
last = tot = 0;
memset(ch[0], -1, sizeof ch[0]);
pre[0] = -1; val[0] = 0;
minl[0] = maxl[0] = 0;
}
void extend(int c){
int p = last, np = ++tot;
val[np] = val[p] + 1;
memset(ch[np], -1, sizeof ch[np]);
minl[np] = maxl[np] = val[np];
while(~p && ch[p][c] == -1) ch[p][c] = np, p = pre[p];
if(p == -1) pre[np] = 0;
else{
int q = ch[p][c];
if(val[q] != val[p] + 1){
int nq = ++tot;
memcpy(ch[nq], ch[q], sizeof ch[q]);
val[nq] = val[p] + 1;
minl[nq] = maxl[nq] = val[nq];
pre[nq] = pre[q];
pre[q] = pre[np] = nq;
while(~p && ch[p][c] == q) ch[p][c] = nq, p = pre[p];
}
else pre[np] = q;
}
last = np;
}
void build(const string &s)
{
init();
for(int i=0;i<s.size();i++) extend(s[i]-'a');
}
void Tsort(const string &s){
for (int i=0;i<=tot;i++) sum[val[i]]++ ;
for (int i=1;i<=s.size();i++) sum[i]+=sum[i-1];
for (int i=0;i<=tot;i++) temp[sum[val[i]]--]=i;
// for (int i=1;i<=tot+1;i++) printf("%d %d\n",temp[i],val[temp[i]]);
}
void _find(const string &s){
int sz = s.size(), u = 0, tmp = 0, c, i;
for(i = 0; i <= tot; i++) maxl[i] = 0;
for(i = 0; i < sz; i++){
c = s[i] - 'a';
if(~ch[u][c]) tmp++, u = ch[u][c];
else{
while(~u && ch[u][c] == -1) u = pre[u];
if(~u) tmp = val[u] + 1, u = ch[u][c];
else tmp = 0, u = 0;
}
maxl[u] = max(maxl[u], tmp);
}
// for(int i=0;i<=tot;i++) printf("%d ",maxl[i]);printf("\n");
// printf("%d\n",val[pre[temp[tot+1]]]);
for(i = tot+1; i >= 2; i--)if(maxl[temp[i]]) maxl[pre[temp[i]]]=val[pre[temp[i]]];
// for(int i=0;i<=tot;i++) printf("%d ",maxl[i]);
for(i = 0; i <= tot; i++) minl[i] = min(minl[i], maxl[i]);
}
int calc(){
int res = 0;
for(int i = 0; i <= tot; i++) res = max(res, minl[i]);
return res;
}
} sam;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int n, i;
cin >> s;
sam.build(s);
sam.Tsort(s);
while(cin >> s) sam._find(s);
cout << sam.calc() << endl;;
return 0;
}