Poj--3080(KMP,枚举)

2014-12-13 03:24:45

思路:以第一个串为准,在其中枚举子串,然后看看其他m-1个串中是否包含这个字串即可,这个过程采用KMP。O(60*60*9*60)

 1 /*************************************************************************
 2     > File Name: 3080.cpp
 3     > Author: Natureal
 4     > Mail: 564374850@qq.com 
 5     > Created Time: Sat 13 Dec 2014 01:09:09 AM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <vector>
13 #include <map>
14 #include <set>
15 #include <stack>
16 #include <queue>
17 #include <iostream>
18 #include <algorithm>
19 using namespace std;
20 #define lp (p << 1)
21 #define rp (p << 1|1)
22 #define getmid(l,r) (l + (r - l) / 2)
23 #define MP(a,b) make_pair(a,b)
24 typedef long long ll;
25 typedef unsigned long long ull;
26 const int INF = 1 << 30;
27 
28 int n,m;
29 int P[70];
30 char g[20][70];
31 char ans[70];
32 
33 void Get_P(char *s,int len){
34     P[0] = -1;
35     int j = -1;
36     for(int i = 1; i < len; ++i){
37         while(j > -1 && s[j + 1] != s[i]) j = P[j];
38         if(s[j + 1] == s[i]) j++;
39         P[i] = j;
40     }
41 }
42 
43 bool Solve(char *s,int len){
44     Get_P(s,len);
45     for(int k = 1; k < m; ++k){
46         int flag = 0;
47         int j = -1;
48         for(int i = 0; i < 60; ++i){
49             while(j > -1 && s[j + 1] != g[k][i]) j = P[j];
50             if(s[j + 1] == g[k][i]) j++;
51             if(j == len - 1){
52                 flag = 1;
53                 break;
54             }
55         }
56         if(flag == 0) return false;
57     }
58     return true;
59 }
60 
61 int main(){
62     scanf("%d",&n);
63     while(n--){
64         ans[0] = '\0';
65         scanf("%d",&m);
66         for(int i = 0; i < m; ++i){
67             scanf("%s",g[i]);
68         }
69         int len;
70         for(len = 60; len >= 3; --len){
71             bool judge = false;
72             for(int i = 0; i + len - 1 < 60; ++i){
73                 bool tmp = Solve(&g[0][i],len);
74                 if(tmp){
75                     judge = true;
76                     char str[70];
77                     memcpy(str,&g[0][i],len * sizeof(char));
78                     str[len] = '\0';
79                     if(ans[0] == '\0' || strcmp(str,ans) < 0)
80                         memcpy(ans,str,sizeof(str));
81                 }
82             }
83             if(judge){
84                 printf("%s\n",ans);
85                 break;
86             }
87         }
88         if(len < 3) printf("no significant commonalities\n");
89     }
90     return 0;
91 }

 

posted @ 2014-12-13 03:25  Naturain  阅读(111)  评论(0编辑  收藏  举报