题意:给定m(m<=10)个长度固定(长度都为60)的串,求这m个串的最长公共子串(要求长度大于等于3)。如果有多种可能,则输出字典序最小的。(3450题意基本相同,只是每个串的长度可变,而且不要求公共串的长度大于等于3)
思路:暴力找出第一个串的所有长度大于等于3的子串,用KMP算法求其是否为剩下m-1个串的子串。为了复用next数组,枚举子串时先固定起点(求一遍next数组即可),然后由长到短枚举子串(剪枝)。
#include <cstdio>
#include <cstring>
using namespace std;
#define N 60
char s[12][N+5],t[N+5],res[N+5];
int next[N+5],len;
int T,n;
void getnext(char *str){
int i,k;
k = next[0] = -1;
for(i = 1;str[i]!='\0';i++){
while(k>-1 && str[k+1] != str[i])
k = next[k];
if(str[k+1] == str[i])
k++;
next[i] = k;
}
}
int test(char *s,char *t,int d){
int i,k;
for(i = 0,k = -1;i<N;i++){
while(k>-1 && t[k+1]!=s[i])
k = next[k];
if(t[k+1] == s[i])
k++;
if(k == d)
return 1;
}
return 0;
}
int match(char *str,int d){
int i;
for(i = 1;i<n;i++)
if(!test(s[i],str,d))
return 0;
return 1;
}
int main(){
scanf("%d",&T);
while(T--){
int i,j;
len = 0;
scanf("%d",&n);
scanf("%s",t);
for(i = 1;i<n;i++)
scanf("%s",s[i]);
for(i = 0;i<N-2 && N-i>=len;i++){
getnext(t+i);
for(j = N-1;j>=i+2 && j-i+1>=len;j--){
if(match(t+i,j-i)){ //如果是后面m-1的串的子串
if(j-i+1>len){
strcpy(res,t+i);
len = j-i+1;
}
else if(strcmp(res,t+i)>0)
strcpy(res,t+i);
break;
}
}
}
if(!len)
printf("no significant commonalities");
else
for(i = 0;i<len;i++)
putchar(res[i]);
printf("\n");
}
return 0;
}
3450:
#include <cstdio>
#include <cstring>
using namespace std;
#define N 4005
#define M 200
char s[N][M+5],t[M+5];
int n,len,next[M+5],rl;
char res[M+5];
void getnext(char *s){
int i,k;
k = next[0] = -1;
for(i = 1;s[i]!='\0';i++){
while(k > -1 && s[k+1] != s[i])//while写成了if居然看了半天才看出来,ORZ
k = next[k];
if(s[k+1] == s[i])
k++;
next[i] = k;
}
}
int test(char *s,char *t,int p){
int i,k;
for(i = 0,k = -1;s[i]!='\0';i++){
while(k>-1 && s[i] != t[k+1])
k = next[k];
if(s[i] == t[k+1])
k++;
if(k==p)
return 1;
}
return 0;
}
int match(char *t,int p){
int i;
for(i = 1;i<n;i++)
if(!test(s[i],t,p))
return 0;
return 1;
}
int main(){
while(scanf("%d",&n) && n){
int i,j;
rl = 0;
scanf("%s",t);
len = (int)strlen(t);
for(i = 1;i<n;i++)
scanf("%s",s[i]);
for(i = 0;i<len;i++){
getnext(t+i);
for(j = len-1;j>=i && j-i+1>=rl;j--)
if(match(t+i,j-i)){
if(j-i+1 > rl){
rl = j-i+1;
strcpy(res,t+i);
}else if(strcmp(res,t+i) > 0)
strcpy(res, t+i);
break;
}
}
if(!rl)
printf("IDENTITY LOST");
else
for(i = 0;i<rl;i++)
putchar(res[i]);
putchar('\n');
}
return 0;
}