# include <stdio.h> # include <algorithm> # include <cstring> using namespace std; int next[100]; char pat[100]; char a[100][100]; int ma; int lenp; int n; void Getnext() { int i=0,j=-1; next[0]=-1; while(i<=lenp) { if(j==-1||pat[j]==pat[i]) j++,i++,next[i]=j; else j=next[j]; } } void kmp() { int k,i,j,m; Getnext(); ma=100; for(k=1; k<n; k++) //匹配剩下的字符串 { i=0; j=0; m=0; while(i<60&&j<lenp)//每个匹配的最长长度 { if(j==-1||pat[j]==a[k][i]) { i++; j++; } else j=next[j]; if(j>m) m=j; } if(ma>m)//都要匹配中的最短 ma=m; } } int main() { int t, i; char result[100]; char tmp[100]; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0; i<n; i++) scanf("%s",a[i]); int ans=0; for(i=0; i<=59; i++) { strcpy(pat,a[0]+i);// 枚举第一个串的所有后缀串,strcpy lenp=60-i; kmp(); if(ma>ans) { ans=ma; strncpy(result,a[0]+i,ans);//strcnpy result[ans]='\0'; } else if(ma==ans)//输出字典序最小 { strncpy(tmp,a[0]+i,ans); tmp[ans]='\0'; if(strcmp(tmp,result)<0) strcpy(result,tmp); } } if(ans>=3) printf("%s\n",result); else printf("no significant commonalities\n"); } return 0; }
poj 3080 Blue Jeans (kmp暴力),布布扣,bubuko.com
原文地址:http://blog.csdn.net/lp_opai/article/details/38586275