BZOJ2946 [Poi2000]公共串(后缀自动机)

时间:2023-03-08 23:21:37
BZOJ2946 [Poi2000]公共串(后缀自动机)

Description

       给出几个由小写字母构成的单词,求它们最长的公共子串的长度。
任务:
l        读入单词
l        计算最长公共子串的长度
l        输出结果

Input

文件的第一行是整数 n,1<=n<=5,表示单词的数量。接下来n行每行一个单词,只由小写字母组成,单词的长度至少为1,最大为2000。

Output

仅一行,一个整数,最长公共子串的长度。

Sample Input

3
abcb
bca
acbc

Sample Output

HINT

Source

其实这题我没A因为权限号密码忘了 但是在COGS过了那就发一下吧。。  已AC

感觉很zz啊,和单个串有什么区别。

那就直接把除了第一个串之外的SAM建出来然后枚举第一个串暴力匹配求最小就好了

1Ahhh

update:

??为什么网上的题解都和我不一样??

这题好像只建一个SAM就行了??!!感觉自己好菜啊。。。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = * , INF = 1e9 + ;
inline int read() {
char c = getchar(); int x = , f = ;
while(c < '' || c > '') {if(c == '-') f = -; c = getchar();}
while(c >= '' && c <= '') x = x * + c - '', c = getchar();
return x * f;
}
struct SuffixAut {
int fa[MAXN], len[MAXN], ch[MAXN][], tot, last, root, ans, cur;
SuffixAut() { cur = tot = last = root = ; ans = ;}
void insert(int x) {
int now = ++tot, pre = last; last = now;
len[now] = len[pre] + ;
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] + ) fa[now] = q;
else {
int nows = ++tot;
memcpy(ch[nows], ch[q], sizeof(ch[q]));
fa[nows] = fa[q]; fa[q] = fa[now] = nows; len[nows] = len[pre] + ;
for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nows;
}
}
}
int work(int x) {
if(ch[cur][x]) {cur = ch[cur][x]; ans++; return ans;}
for(; cur && !ch[cur][x]; cur = fa[cur]);
if(!cur) cur = root, ans = ;
else ans = len[cur] + , cur = ch[cur][x];
return ans;
}
}Suf[];
char s[][MAXN];
int N[];
int main() {
#ifdef WIN32
freopen("a.in", "r", stdin);
#else
freopen("pow.in", "r", stdin);
freopen("pow.out", "w", stdout);
#endif
int num = read();
for(int i = ; i <= num; i++) scanf("%s", s[i] + ), N[i] = strlen(s[i] + );
for(int i = ; i <= num; i++)
for(int j = ; j <= N[i]; j++)
Suf[i].insert(s[i][j] - 'a');
int out = ;
for(int i = ; i <= N[]; i++) {
int ans = INF;
for(int j = ; j <= num; j++)
ans = min(ans, Suf[j].work(s[][i] - 'a'));
out = max(out, ans);
}
printf("%d", out);
return ;
}