hdu1238 kmp

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. 

InputThe 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. 
OutputThere 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
题意:找n个字符串里的公共子串,相反方向的也算公共子串
题解:枚举第一个的子串和后面的进行kmp
(1a的感觉真tm爽)
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 10007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1 using namespace std; const double g=10.0,eps=1e-;
const int N=+,maxn=(<<)-,inf=0x3f3f3f3f; int Next[N],slen,plen;
string a[N],ptr,str; void getnext()
{
int k=-;
Next[]=-;
for(int i=;i<slen;i++)
{
while(k>-&&str[k+]!=str[i])k=Next[k];
if(str[k+]==str[i])k++;
Next[i]=k;
}
}
bool kmp()
{
int k=-;
for(int i=;i<plen;i++)
{
while(k>-&&str[k+]!=ptr[i])k=Next[k];
if(str[k+]==ptr[i])k++;
if(k==slen-)return ;
}
return ;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie();
// cout<<setiosflags(ios::fixed)<<setprecision(2);
int t,n;
cin>>t;
while(t--){
cin>>n;
for(int i=;i<n;i++)cin>>a[i];
int ans=;
for(int i=;i<=a[].size();i++)
{
for(int j=;j<=a[].size()-i;j++)
{
str=a[].substr(j,i);
slen=str.size();
getnext();
bool flag=;
for(int k=;k<n;k++)
{
ptr=a[k];
plen=a[k].size();
if(kmp())continue;
reverse(ptr.begin(),ptr.end());
if(kmp())continue;
flag=;
break;
}
if(flag)ans=max(ans,slen);
}
}
cout<<ans<<endl;
}
return ;
}
上一篇:C#反射实例应用--------获取程序集信息和通过类名创建类实例


下一篇:ThoughtWorks西邮暑期特训营 -- JavaScript在线笔试题