Poj--1226(KMP,枚举)

2014-12-15 20:32:06

思路:简单的KMP,枚举下就好。

 1 /*************************************************************************
 2     > File Name: p1226.cpp
 3     > Author: Natureal
 4     > Mail: 564374850@qq.com 
 5     > Created Time: Sun 14 Dec 2014 12:19:55 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 t,n;
29 int P1[110],P2[110];
30 char g[110][110];
31 
32 bool Solve(char *s1,char *s2,int l){
33     P1[0] = P2[0] = -1;
34     int j = -1;
35     for(int i = 1; i < l; ++i){
36         while(j > -1 && s1[j + 1] != s1[i]) j = P1[j];
37         if(s1[j + 1] == s1[i]) j++;
38         P1[i] = j;
39     }
40     j = -1;
41     for(int i = 1; i < l; ++i){
42         while(j > -1 && s2[j + 1] != s2[i]) j = P2[j];
43         if(s2[j + 1] == s2[i]) j++;
44         P2[i] = j;
45     }
46     for(int k = 0; k < n; ++k){
47         int j = -1,flag = 0;
48         int len = strlen(g[k]);
49         for(int i = 0; i < len; ++i){
50             while(j > -1 && s1[j + 1] != g[k][i]) j = P1[j];
51             if(s1[j + 1] == g[k][i]) j++;
52             if(j >= l - 1){
53                 flag = 1;
54                 break;
55             }
56         }
57         if(flag) continue;
58         j = -1;
59         for(int i = 0; i < len; ++i){
60             while(j > -1 && s2[j + 1] != g[k][i]) j = P2[j];
61             if(s2[j + 1] == g[k][i]) j++;
62             if(j >= l - 1){
63                 flag = 1;
64                 break;
65             }
66         }
67         if(!flag) return false;
68     }
69     return true;
70 }        
71 
72 int main(){
73     scanf("%d",&t);
74     while(t--){
75         scanf("%d",&n);
76         for(int i = 0; i < n; ++i)
77             scanf("%s",g[i]);
78         int len = strlen(g[0]);
79         int ans = 0;
80         for(int l = len; l >= 1; --l){
81             for(int i = 0; i + l - 1 < len; ++i){
82                 char tmp[110];
83                 for(int j = 0; j < l; ++j) tmp[j] = g[0][i + l - 1 - j];
84                 if(Solve(&g[0][i],tmp,l)){
85                     ans = l;
86                     break;
87                 }
88             }
89             if(ans) break;
90         }
91         printf("%d\n",ans);
92     }
93     return 0;
94 }

 

posted @ 2014-12-15 20:32  Naturain  阅读(146)  评论(0编辑  收藏  举报