hdu1238 Substrings
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1238
题目:
Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10245 Accepted Submission(s): 4879
Problem Description
You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
Input
The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
Output
There should be one line per test case containing the length of the largest string found.
Sample Input
2
3
ABCD
BCDFF
BRCD
2
rose
orchid
Sample Output
2
2
Author
Asia 2002, Tehran (Iran), Preliminary
Recommend
Eddy
思路:暴力枚举+kmp
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 #define MP make_pair
6 #define PB push_back
7 typedef long long LL;
8 typedef pair<int,int> PII;
9 const double eps=1e-8;
10 const double pi=acos(-1.0);
11 const int K=1e6+7;
12 const int mod=1e9+7;
13
14 int nt[K];
15 char sa[105][105],sb[105],sc[105];
16 void kmp_next(char *T,int *next)
17 {
18 next[0]=0;
19 for(int i=1,j=0,len=strlen(T);i<len;i++)
20 {
21 while(j&&T[i]!=T[j]) j=next[j-1];
22 if(T[i]==T[j]) j++;
23 next[i]=j;
24 }
25 }
26 int kmp(char *S,char *T,int *next)
27 {
28 int ans=0;
29 int ls=strlen(S),lt=strlen(T);
30 kmp_next(T,next);
31 for(int i=0,j=0;i<ls;i++)
32 {
33 while(j&&S[i]!=T[j]) j=next[j-1];
34 if(S[i]==T[j]) j++;
35 if(j==lt) ans++;
36 }
37 return ans;
38 }
39 int main(void)
40 {
41 int t,n;cin>>t;
42 while(t--)
43 {
44 cin>>n;
45 for(int i=1;i<=n;i++)
46 scanf("%s",sa[i]);
47 int len=strlen(sa[1]),ans=0;
48 for(int i=0;i<len;i++)
49 {
50 for(int j=i;j<len;j++)
51 {
52 int ff=1;
53 sb[j-i]=sa[1][j],sb[j-i+1]='\0';
54 if(j-i+1<=ans)continue;
55 for(int k=j;k>=i;k--)
56 sc[j-k]=sa[1][k];
57 sc[j-i+1]='\0';
58 for(int k=2;k<=n&&ff;k++)
59 if(!kmp(sa[k],sb,nt)&&!kmp(sa[k],sc,nt))
60 ff=0;
61 if(ff)
62 ans=j-i+1;
63 }
64 }
65 printf("%d\n",ans);
66 }
67 return 0;
68 }
作者:weeping
出处:www.cnblogs.com/weeping/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。