题意 求两个串的LCS长度
我们先用第一个串建立自动机 然后跑第二个串
第二个串怎么跑呢 如果有匹配 类似字典树一样往下面找 len++
如果不能匹配 要去parent树父母那里找 因为长后缀不包含这个可能短后缀包含 找到就另len等于当前的maxlen 否则如果到根了 让len 为0
/*
if you can't see the repay
Why not just work step by step
rubbish is relaxed
to ljq
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cmath>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define dbg(x) cout<<#x<<" = "<< (x)<< endl
#define dbg2(x1,x2) cout<<#x1<<" = "<<x1<<" "<<#x2<<" = "<<x2<<endl
#define dbg3(x1,x2,x3) cout<<#x1<<" = "<<x1<<" "<<#x2<<" = "<<x2<<" "<<#x3<<" = "<<x3<<endl
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
const int MAX_N = 400010;
char str[MAX_N],str_[MAX_N];
int len,len_;
struct SAM
{
int fa[MAX_N],ch[MAX_N][26],maxlen[MAX_N],tot,last;
void init()
{
tot = last = 1;maxlen[1] = fa[1] = 0;
memset(ch[1],0,sizeof(ch[1]));
}
void add(int x)
{
int np = ++tot,p = last;last = np;
maxlen[np] = maxlen[p] + 1;
memset(ch[np],0,sizeof(ch[np]));
while(p&&!ch[p][x]) ch[p][x] = np,p = fa[p];
if(!p) fa[np] = 1;
else
{
int q = ch[p][x];
if(maxlen[q]==maxlen[p]+1) fa[np] = q;
else
{
int nq = ++tot;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
fa[nq] = fa[q],fa[np] = fa[q] = nq;
maxlen[nq] = maxlen[p] + 1;
while(p&&ch[p][x]==q) ch[p][x]=nq,p = fa[p];
}
}
}
void solve()
{
int np = 1,len = 0,ans = 0;
for(int i = 0;i<len_;++i)
{
int x = str_[i] - 'a';
while(np&&!ch[np][x]) np = fa[np] , len = maxlen[np];
if(!np) np = 1,len = 0;
if(ch[np][x]) np = ch[np][x], len++;
ans = max(ans,len);
}
printf("%d\n",ans);
}
}S;
int main()
{
//ios::sync_with_stdio(false);
//freopen("a.txt","r",stdin);
//freopen("b.txt","w",stdout);
scanf("%s",str);
scanf("%s",str_);
len = strlen(str);
len_ = strlen(str_);
S.init();
for(int i = 0;i<len;++i) S.add(str[i]-'a');
S.solve();
//fclose(stdin);
//fclose(stdout);
//cout << "time: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
return 0;
}