给n个串(n>=2&&n<=10),每个串长度都是60,然后问所有串的最长公共子串,如果答案不唯一输出字典序最小的。
思路:直接暴力,枚举+KMP,后缀数组
枚举+KMP
#include<stdio.h>
#include<string.h>
char a[12][62] ,b[62];
int next[62];
void Get_Next(char b[])
{
int m = strlen(b);
int j = 0 ,k = -1;
next[0] = -1;
while(j < m)
{
if(k == -1 || b[j] == b[k])
next[++j] = ++k;
else k = next[k];
}
return ;
}
bool KMP(char a[] ,char b[])
{
int n = strlen(a);
int m = strlen(b);
int i ,j;
for(i = j = 0 ;i < n ;)
{
if(a[i] == b[j])
{
if(j == m - 1) return 1;
i ++ ,j ++;
}
else
{
j = next[j];
if(j == -1)
i ++ ,j = 0;
}
}
return 0;
}
int main ()
{
int t ,n ,i ,j ,k ,mk;
scanf("%d" ,&t);
char ans[62];
while(t--)
{
scanf("%d" ,&n);
for(i = 1 ;i <= n ;i ++)
scanf("%s" ,a[i]);
for(mk = i = 0 ;i < 60 ;i ++)
for(j = i ;j < 60 ;j ++)
{
for(k = i ;k <= j ;k ++)
b[k-i] = a[1][k];
b[j-i+1] = ' ';
Get_Next(b);
for(k = 2 ;k <= n ;k ++)
if(!KMP(a[k] ,b)) break;
if(k == n + 1)
{
if(!mk || strlen(b) > strlen(ans) || strlen(b) == strlen(ans) && strcmp(b ,ans) < 0)
{
int len = strlen(b);
for(k = 0 ;k <= len ;k ++)
ans[k] = b[k];
mk = 1;
}
}
}
if(!mk || strlen(ans) < 3)
printf("no significant commonalities
");
else printf("%s
" ,ans);
}
return 0;
}