/* 最长公共子串 用后缀自动机实现 首先建立一个串的后缀自动机 然后用另一个串在上面跑自动机即可 */ #include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #define M 500010 using namespace std; char s[M]; int ch[M][26], fa[M], len[M], last = 1, node = 1; void insert(int c) { int f = last, p = ++node; last = p; len[p] = len[f] + 1; while(f && !ch[f][c]) ch[f][c] = p, f = fa[f]; if(f == 0)fa[p] = 1; else { int x = ch[f][c]; if(len[x] == len[f] + 1) fa[p] = x; else { int nx = ++node; fa[nx] = fa[x]; len[nx] = len[f] + 1; fa[p] = fa[x] = nx; memcpy(ch[nx], ch[x], sizeof(ch[nx])); } } } int main() { scanf("%s", s); int l = strlen(s); for(int i = 0; i < l; i++) insert(s[i] - ‘a‘); scanf("%s", s); l = strlen(s); int ans = 0; int now = 1, tmp = 0; for(int i = 0; i < l; i++) { int op = s[i] - ‘a‘; if(ch[now][op]) { now = ch[now][op]; tmp++; } else { while(now && !ch[now][op]) now = fa[now]; if(now == 0) tmp = 0,now = 1; else tmp = len[now] + 1, now = ch[now][op]; } ans = max(ans, tmp); } cout << ans << "\n"; return 0 ; }
原文:https://www.cnblogs.com/luoyibujue/p/9245555.html