标签:
Description
Input
Output
Sample Input
3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA 3 CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Sample Output
no significant commonalities AGATAC CATCATCAT
题意及题解转自:http://blog.csdn.net/qiqijianglu/article/details/7851454
题意:求n个字符串的最长公共串。
求n个字符长度最长公共子串。对于多模式匹配问题,一般是不可以用KMP解决得,因为忒暴力。
思路很简单:我们先按字符串的长度由短到长进行快排。枚举第一个字符串的不同长度子串,判断她是否为下面多有的公共子串?如果是的话,那么我们就表明找到,则比较其长度,如果比已经找到的串长,那么就替换结果串 否则按字典序比较。取字典序考前的,就可以。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdlib> 4 #include<cstdio> 5 #include<algorithm> 6 #include<cmath> 7 #include<queue> 8 #include<map> 9 #include<set> 10 #include<stack> 11 #include<string> 12 13 #define N 65 14 #define M 105 15 #define mod 10000007 16 //#define p 10000007 17 #define mod2 1000000000 18 #define ll long long 19 #define LL long long 20 #define eps 1e-6 21 #define inf 100000000 22 #define maxi(a,b) (a)>(b)? (a) : (b) 23 #define mini(a,b) (a)<(b)? (a) : (b) 24 25 using namespace std; 26 27 int T; 28 int n; 29 char text[N][N]; 30 char result[N]; 31 int ma; 32 int l; 33 int le; 34 char pat[N]; 35 int next[N]; 36 int mma; 37 38 void ini() 39 { 40 int i; 41 ma=-1; 42 scanf("%d",&n); 43 for(i=1;i<=n;i++){ 44 scanf("%s",text[i]); 45 } 46 l=strlen(text[1]); 47 } 48 49 void get_next() 50 { 51 memset(next,-1,sizeof(next)); 52 int i,j; 53 j=-1;next[0]=-1; 54 i=0; 55 while(i<le) 56 { 57 if(j==-1 || pat[i]==pat[j]){ 58 i++;j++;next[i]=j; 59 } 60 else{ 61 j=next[j]; 62 } 63 } 64 } 65 66 void KMP() 67 { 68 int i,j,k,m; 69 mma=200; 70 for(k=2;k<=n;k++){ 71 i=0;j=0;m=0; 72 while(i<l && j<le) 73 { 74 if(j==-1 || text[k][i]==pat[j]) 75 { 76 i++;j++; 77 m=max(m,j); 78 } 79 else{ 80 j=next[j]; 81 } 82 } 83 mma=min(m,mma); 84 } 85 } 86 87 void solve() 88 { 89 int i; 90 char te[N]; 91 for(i=0;i<l;i++){ 92 strcpy(pat,text[1]+i); 93 le=strlen(pat); 94 get_next(); 95 KMP(); 96 if(mma>ma){ 97 ma=mma; 98 strncpy(result,text[1]+i,ma); 99 result[ma]=‘\0‘; 100 } 101 else if(mma==ma){ 102 strncpy(te,text[1]+i,ma); 103 result[ma]=‘\0‘; 104 if(strcmp(te,result)==-1){ 105 strcpy(result,te); 106 } 107 } 108 } 109 } 110 111 void out() 112 { 113 if(ma<3){ 114 printf("no significant commonalities\n"); 115 } 116 else{ 117 printf("%s\n",result); 118 } 119 } 120 121 int main() 122 { 123 //freopen("data.in","r",stdin); 124 //freopen("data.out","w",stdout); 125 scanf("%d",&T); 126 //for(int ccnt=1;ccnt<=T;ccnt++) 127 while(T--) 128 //scanf("%d%d",&n,&m); 129 //while(scanf("%s",s)!=EOF) 130 { 131 ini(); 132 solve(); 133 out(); 134 } 135 return 0; 136 }
标签:
原文地址:http://www.cnblogs.com/njczy2010/p/4287753.html