Substrings
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9258 | Accepted: 3177 |
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 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
Source
题意:求n个字符串的最长公共串,包括反串。
要枚举一个最短的字符串的所有子串。
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<string.h>
#include<memory.h>
using namespace std;
char ss[110][110];
int fail[110];
int kmp(char *str,char *pat)
{
int i,j,k;
memset(fail,-1,sizeof(fail));
for(i=1;pat[i];i++)
{
for(k=fail[i-1];k>=0&&pat[i]!=pat[k+1];k=fail[k]) ;
if(pat[k+1]==pat[i]) fail[i]=k+1;
}
i=j=0;
while(str[i]&&pat[j])
{
if(pat[j]==str[i]) ++i,++j;
else if(j==0) ++i;
else j=fail[j-1]+1;
}
if(pat[j]) return -1;
else return i-j;
}
int main()
{
int t,n;
char yes[110],no[110],sho[110];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int maxn=110;
int l,q;
for(int i=0;i<n;i++)
{
scanf("%s",ss[i]);
l=strlen(ss[i]);
if(l<maxn)
{maxn=l;q=i;}
}
strcpy(sho,ss[q]);
l=strlen(ss[q]);
//cout<<sho<<"&"<<endl;
bool flag=false;
while(maxn)
{
for(int i=0;i<=l-maxn;i++)
{
strncpy(yes,sho+i,maxn);
yes[maxn]='\0';
//cout<<yes<<"*"<<endl;
for(int j=0;j<maxn;j++)
no[j]=yes[maxn-j-1];
no[maxn]='\0';
//cout<<no<<endl;
int kk;
for(kk=0;kk<n;kk++)
{
if(!(kmp(ss[kk],yes)>=0||kmp(ss[kk],no)>=0))
break;
}
if(kk>=n)
{
flag=true;break;
}
}
if(flag)break;
maxn--;
}
printf("%d\n",maxn);
}
}