题意:求两个串的LCS
思路:对其中一个建SAM,另一个在上面跑。如果跑不了了就走后缀链接,注意这时候在字符串前面删除了 >= 1 个字母。
串长变为 对应状态所表示的最长串。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 250005;
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 str1[maxn],str2[maxn];
int main(){
g.init();
scanf("%s%s",str1+1,str2+1);
int len = strlen( str2+1 );
for( int i = 1;i <= len;i++ ){
g.extend( str2[i]-'a' );
}
len = strlen( str1+1 );
int p = 0;
int L = 0;
for( int i = 1;i <= len;i++ ){
int c = str1[i]-'a';
while( p && !g.ch[p][c] ) {
p = g.fa[p];L =g.len[p] ;
}
p = g.ch[p][c];
if(p) L++;
ans = max( L,ans );
}
if(ans)printf("%d\n",ans);
else puts("0");
return 0;
};