SP1811 LCS - Longest Common Substring
阿新 • • 發佈:2019-01-10
\(\color{#0066ff}{ 題目描述 }\)
輸入2 個長度不大於250000的字串,輸出這2 個字串的最長公共子串。如果沒有公共子串則輸出0 。
\(\color{#0066ff}{輸入格式}\)
兩個字串
\(\color{#0066ff}{輸出格式}\)
一個整數,為 所求答案
\(\color{#0066ff}{輸入樣例}\)
alsdfkjfjkdsal
fdjskalajfkdsla
\(\color{#0066ff}{輸出樣例}\)
3
\(\color{#0066ff}{資料範圍與提示}\)
none
\(\color{#0066ff}{ 題解 }\)
對第一個串建立字尾自動機
用第二個串在自動機上跑匹配
匹配一下就取max
#include<bits/stdc++.h> using namespace std; #define LL long long LL in() { char ch; int x = 0, f = 1; while(!isdigit(ch = getchar()))(ch == '-') && (f = -f); for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48)); return x * f; } const int maxn = 6e5 + 5; struct SAM { protected: struct node { node *ch[26], *fa; int len, siz; node(int len = 0, int siz = 0): fa(NULL), len(len), siz(siz) { memset(ch, 0, sizeof ch); } }; node *root, *tail, *lst; node pool[maxn]; void extend(int c) { node *o = new(tail++) node(lst->len + 1, 1), *v = lst; for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o; if(!v) o->fa = root; else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c]; else { node *n = new(tail++) node(v->len + 1), *d = v->ch[c]; std::copy(d->ch, d->ch + 26, n->ch); n->fa = d->fa, d->fa = o->fa = n; for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n; } lst = o; } void clr() { tail = pool; root = lst = new(tail++) node(); } public: SAM() { clr(); } void ins(char *s) { for(char *p = s; *p; p++) extend(*p - 'a'); } int match(char *s) { int ans = 0; node *o = root; int len = 0; for(char *p = s; *p; p++) { int pos = *p - 'a'; if(o->ch[pos]) o = o->ch[pos], len++; else { while(o && !o->ch[pos]) o = o->fa; if(!o) o = root, len = 0; else len = o->len + 1, o = o->ch[pos]; } ans = std::max(ans, len); } return ans; } }sam; char s[maxn]; int main() { scanf("%s", s); sam.ins(s); scanf("%s", s); printf("%d\n", sam.match(s)); return 0; }