Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6817 Accepted Submission(s): 3050
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
题意:找出最长公共串(正串或反串)的长度:
1:先对于串的长度排序,找出最小的那个串(最长的公共串一定是最短串的子串);
2:遍历最短串的子串,和其他的串匹配:记录最长的长度;
3:求出反串,遍历反串的子串,记录最长的长度;
4:输出两个长度较大的那个.
代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<memory.h>
#include<stdlib.h>
using namespace std;
struct string1
{
int len;
int num;
} sl[101];
char c[101];
char s[101][101];
int cmp(const void *a,const void *b)
{
string1 *p=(string1 *)a,*p1=(string1 *)b;
return p->len-p1->len;
}
int cmp1(const void *a,const void *b)
{
return *(int *)b-*(int *)a;
}
char *substring1(char a[],int n,int m)//求子串
{
int i,j;
memset(c,'\0',sizeof(c));
for(i=n,j=0; i<m; i++,j++)
{
c[j]=a[i];
}
return c;
}
void convert(char a[])//求反串
{
int i,k;
char c;
k=strlen(a);
for(i=0; i<k/2; i++)
{
c=a[i];
a[i]=a[k-i-1];
a[k-i-1]=c;
}
}
int findstring(char s1[],int n)
{
int length[101],s_len,sub,i,j,k;
char substring[101];
memset(substring,'\0',sizeof(substring));
strcpy(substring,s1);
memset(length,0,sizeof(length));
s_len=strlen(substring);
for(sub=0; sub<sl[0].len; )
{
for(i=1; i<n; i++)
{
for(j=0,k=0; j<sl[i].len; j++)
{
if(s[sl[i].num][j]!=substring[k])
{
k=0;
continue;
}
else if(s[sl[i].num][j]==substring[k])
{
k++;
}
if(k>=s_len)
{
break;
}
}
if(k<s_len)
{
strcpy(substring,substring1(s[sl[0].num],0,s_len-1));
s_len=strlen(substring);
if(s_len==0)
break;
i=0;
}
}
length[sub]=strlen(substring);
sub++;
strcpy(substring,substring1(s[sl[0].num],1,sl[0].len));
strcpy(s[sl[0].num],substring);
s_len=strlen(substring);
}
qsort(length,sub,sizeof(int),cmp1);
return length[0];
}
int main()
{
int t,n,i,MAX,max;
char substr[101],substring[101];
while(~scanf("%d",&t))
{
while(t--)
{
scanf("%d",&n);
memset(s,'\0',sizeof(s[0])*101);
for(i=0; i<n; i++)
{
scanf("%s",s[i]);
sl[i].len=strlen(s[i]);
sl[i].num=i;
}
qsort(sl,n,sizeof(string1),cmp);
strcpy(substr,s[sl[0].num]);
strcpy(substring,s[sl[0].num]);
MAX=findstring(substring,n);
convert(substr);
strcpy(s[sl[0].num],substr);
max=findstring(substr,n);
if(MAX>max)
cout<<MAX<<endl;
else
cout<<max<<endl;
}
}
return 0;
}