[Poi2000]公共串
Description
给出几个由小写字母构成的单词,求它们最长的公共子串的长度。
任务:
l 读入单词
l 计算最长公共子串的长度
l 输出结果
Input
文件的第一行是整数 n,1<=n<=5,表示单词的数量。接下来n行每行一个单词,只由小写字母组成,单词的长度至少为1,最大为2000。
Output
仅一行,一个整数,最长公共子串的长度。
Sample Input
3
abcb
bca
acbc
Sample Output
2
Solution
和SPOJ那个一样
Code
#include <bits/stdc++.h>
using namespace std;
#define rep(i, l, r) for (int i = (l); i <= (r); i++)
#define per(i, r, l) for (int i = (r); i >= (l); i--)
#define MS(_) memset(_, 0, sizeof(_))
#define MP make_pair
#define PB push_back
inline void ckmax(int &x, int y){ if (x < y) x = y; }
inline void ckmin(int &x, int y){ if (x > y) x = y; }
const int INF = 0x7fffffff;
const int N = 200100;
char s[N];
int case_cnt,len[N], nxt[N][26], fa[N], d[N], t[N], f[N], mn[N];
struct sam{
int root, last, cnt, LEN;
sam() { cnt = 0; root = last = ++cnt; }
inline void insert(int c){
int np = ++cnt, p = last; last = np;
mn[np] = len[np] = len[p]+1;
for (; p && !nxt[p][c]; nxt[p][c] = np, p = fa[p]);
if (!p) fa[np] = root;
else if (len[nxt[p][c]] == len[p]+1) fa[np] = nxt[p][c];
else{
int nq = ++cnt, q = nxt[p][c]; mn[nq] = len[nq] = len[p]+1;
memcpy(nxt[nq], nxt[q], sizeof nxt[q]); fa[nq] = fa[q];
fa[q] = fa[np] = nq;
for (; p && nxt[p][c] == q; nxt[p][c] = nq, p = fa[p]);
}
}
inline void build(){ char s[N];
scanf("%d",&case_cnt); case_cnt--;
scanf("%s", s+1); LEN = strlen(s+1);
rep(i, 1, LEN) insert(s[i]-'a');
}
inline void topsort(){
rep(i, 1, cnt) d[len[i]]++;
rep(i, 1, LEN) d[i] += d[i-1];
rep(i, 1, cnt) t[d[len[i]]--] = i;
}
inline bool run(){
scanf("%s", s+1);
MS(f); int _len = strlen(s+1), nowlen = 0;
for (int i = 1, p = root; i <= _len; i++){ int c = s[i]-'a';
if (nxt[p][c]) { nowlen++; p = nxt[p][c]; }
else{
for (; p && !nxt[p][c]; p = fa[p]);
if (!p) { p = root; nowlen = 0; }
else { nowlen = len[p] + 1; p = nxt[p][c]; }
}
ckmax(f[p], nowlen);
}
per(i, cnt, 1){ int now = t[i];
ckmin(mn[now], f[now]);
ckmax(f[fa[now]], f[now]);
}
return true;
}
}SAM;
int main(){
SAM.build();
SAM.topsort();
for(int i=1;i<=case_cnt;i++)SAM.run();
int ans = 0;
rep(i, 1, SAM.cnt) ckmax(ans, mn[i]);
printf("%d\n", ans);
return 0;
}