题意:求多个串的LCS
思路:对一个节点建立SAM,用剩下的字符串在上面跑,注意沿着 后缀链接向上走的时候,长度的变化不是-1,而是变为len[ p ]
,而向下走的时候一定是长度加一。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 100005;
int righ[2*maxn],pos[maxn<<1];
const int ch_size = 26;
int ans;
struct SAM{
int fa[maxn<<1], // 后缀链接
ch[maxn<<1][ch_size],
len[maxn<<1], //该节点最长串的长度
tot, // 节点总数
last; // 代表当前的整个串
void init(){
tot = last = 0;
fa[0] = -1;
len[0] = 0;
memset( ch[0],0,sizeof(ch[0]) );
}
void extend( int x ){
int p = last;
int cur = ++tot;
memset( ch[cur],0,sizeof( ch[cur] ) );
len[cur] = len[last]+1;
while( p != -1 && !ch[p][x] ){
ch[p][x] = cur;
p = fa[p];
}
if( p == -1 ){
fa[cur] = 0;
}else {
int q = ch[p][x];
if (len[q] == len[p] + 1) {
fa[cur] = q;
} else {
int clone = ++tot;
len[clone] = len[p] + 1;
for (int i = 0; i < ch_size; i++) {
ch[clone][i] = ch[q][i];
}
fa[clone] = fa[q];
fa[q] = fa[cur] = clone;
while (p != -1) {
if (ch[p][x] == q)ch[p][x] = clone;
else break;
p = fa[p];
}
}
}
last = cur;
}
}g;
char str[maxn],str2[maxn];
int cnt[maxn<<1],len[maxn<<1],tmp[maxn<<1],c[maxn],b[maxn<<1],Len;
void radix(){
for( int i = 1;i <= g.tot;i++ ) c[ g.len[i] ]++;
for( int i = 2;i <= Len;i++ ) c[i] += c[i-1];
for( int i = 1;i <= g.tot;i++ ) b[ c[ g.len[i] ]-- ] = i;
}
void solve( char* str ){
for( int i = 0;i <= g.tot;i++ ) tmp[i] = 0;
int p = 0,len = strlen(str);
int L = 0;
for( int i = 0;i<len;i++ ){
int c = str[i]-'a';
while( p && !g.ch[p][c] ) {
p = g.fa[p];L = g.len[p];
}
p = g.ch[p][c];
if( p ){
L++;tmp[p] = max(tmp[p],L);
}
}
for( int i = g.tot;i >= 1;i-- ){
tmp[ g.fa[ b[i] ] ] = max( tmp[ g.fa[ b[i] ] ],min( g.len[ g.fa[ b[i] ] ],tmp[ b[i] ] ) );
}
}
int main(){
g.init();
scanf("%s",str2);
Len = strlen(str2);
for( int i = 0;i < Len;i++ ){
g.extend( str2[i]-'a' );
}
radix();
memset( cnt,0x3f,sizeof(cnt) );
while( scanf("%s",str) != EOF ){
int len = strlen(str);
solve( str );
for( int i = 0;i <= g.tot;i++ ) cnt[i] = min( cnt[i],tmp[i] );
}
int ans = 0;
for( int i = 1;i <= g.tot;i++ ) ans = max( ans,cnt[i] );
printf("%d\n",ans);
return 0;
};