A string is finite sequence of characters over a non-empty finite set Σ.this
In this problem, Σ is the set of lowercase letters.spa
Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.code
Now your task is simple, for two given strings, find the length of the longest common substring of them.blog
Here common substring means a substring of two or more strings.input
The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.string
The length of the longest common substring. If such string doesn't exist, print "0" instead.it
Input: alsdfkjfjkdsal fdjskalajfkdsla Output: 3
Notice: new testcases addedio
爲何都說這是後綴自動機的裸題啊。難道就我看不出來麼qwq、、ast
正解其實比較好想,先把第一個串扔到SAM裏面class
對於第二個串依次枚舉,若是能匹配就匹配,不然就沿着parent邊走(怎麼這麼像AC自動機??),順便記錄一下最長長度
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN = 2 * 300000 + 1; char s1[MAXN], s2[MAXN]; int N1, N2, tot = 1, root = 1, last = 1, len[MAXN], ch[MAXN][27], fa[MAXN]; void insert(int x) { int now = ++tot, pre = last; last = now; len[now] = len[pre] + 1; for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now; if(!pre) fa[now] = root; else { int q = ch[pre][x]; if(len[q] == len[pre] + 1) fa[now] = q; else { int nows = ++tot; memcpy(ch[nows], ch[q], sizeof(ch[q])); len[nows] = len[pre] + 1; fa[nows] = fa[q]; fa[now] = fa[q] = nows; for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nows; } } } int main() { #ifdef WIN32 freopen("a.in", "r", stdin); #endif scanf("%s %s", s1 + 1, s2 + 1); N1 = strlen(s1 + 1); N2 = strlen(s2 + 1); for(int i = 1; i <= N1; i++) insert(s1[i] - 'a'); int ans = 0, nowlen = 0, cur = root; for(int i = 1; i <= N2; i++, ans = max(ans, nowlen)) { int p = s2[i] - 'a'; if(ch[cur][p]) {nowlen++, cur = ch[cur][p]; continue;} for(; cur && !ch[cur][p]; cur = fa[cur]); nowlen = len[cur] + 1, cur = ch[cur][p]; } printf("%d\n", ans); return 0; }