poj 3080 Blue Jeans (n个字符串的最长公共子串,暴力+kmp)
题意:给出n个字符串(n<=10),字符串长度不超过70,问出现在全部n个字符串中的最长并且字典序最小的长度大于等于3的子串。
思路:数据范围很小。。。直接暴力枚举+kmp匹配一下。。。
1/* ***********************************************
2Author :111qqz
3Created Time :2016年08月11日 星期四 01时29分02秒
4File Name :code/poj/3080.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <stack>
14#include <set>
15#include <map>
16#include <string>
17#include <cmath>
18#include <cstdlib>
19#include <deque>
20#include <ctime>
21#define fst first
22#define sec second
23#define lson l,m,rt<<1
24#define rson m+1,r,rt<<1|1
25#define ms(a,x) memset(a,x,sizeof(a))
26typedef long long LL;
27#define pi pair < int ,int >
28#define MP make_pair
29
30using namespace std;
31const double eps = 1E-8;
32const int dx4[4]={1,0,0,-1};
33const int dy4[4]={0,-1,1,0};
34const int inf = 0x3f3f3f3f;
35const int N=70;
36int nxt[N];
37string dna[15];
38int n ;
39void getnxt( string a)
40{
41 int i = 0 ;
42 int j = -1;
43 int n = a.length();
44 nxt[0] = -1;
45 while (i<n)
46 if (j==-1||a[i]==a[j]) nxt[++i]=++j;
47 else j = nxt[j];
48}
49bool kmp(string a,string b)
50{
51 int m = a.length();
52 int n = b.length();
53 getnxt(a);
54 int i = 0;
55 int j = 0;
56 while (i<n)
57 {
58 if (j==-1||a[j]==b[i]) i++,j++;
59 else j=nxt[j];
60 if (j==m) return true;
61 }
62 return false;
63}
64int main()
65{
66 #ifndef ONLINE_JUDGE
67 freopen("code/in.txt","r",stdin);
68 #endif
69 int T;
70 ios::sync_with_stdio(false);
71 cin>>T;
72 while (T--)
73 {
74 cin>>n;
75 for ( int i = 1 ; i <= n ; i++) cin>>dna[i];
76 string ans="";
77 int len = dna[1].length();
78 //cout<<"len:"<<len<<endl;
79 for ( int i = 0 ; i < len ; i++)
80 for ( int j = 1 ; i+j-1 < len ;j++)
81 {
82 bool match = true;
83 string tmp = dna[1].substr(i,j);
84 // cout<<"tmp:"<<tmp<<endl;
85
86 for ( int k = 2 ; k <= n; k++)
87 if (!kmp(tmp,dna[k]))
88 {
89 match = false;
90 break;
91 }
92 if (match)
93 {
94 // cout<<"ccc"<<endl;
95 if (tmp.length()>ans.length())
96 ans = tmp;
97 else if (tmp.length()==ans.length()&&tmp<ans)
98 ans = tmp;
99 }
100 }
101 if (ans.length()<3)
102 cout<<"no significant commonalities"<<endl;
103 else
104 cout<<ans<<endl;
105
106 }
107
108 #ifndef ONLINE_JUDGE
109 fclose(stdin);
110 #endif
111 return 0;
112}