Substrings
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 19 Accepted Submission(s) : 10
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
来源: http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?pid=1000&ojid=0&cid=10646&hide=0
详解在注释中
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define MAXN 100*2
#define MAXLen 100*2
struct String
{
string S;
int len;
}Str[MAXN];
int Cal(int n)
{
int Max_Size = INT_MIN;
for(int i=0;i<Str[1].len;i++)
{
for(int j=i;j<Str[1].len;j++) //枚举最小串的每个子串
{
string S(&Str[1].S[i],&Str[1].S[j]+1); //将S初始化为该子串
int flag = 1;
for(int m=2;m<=n;m++) //对其他串及其倒置串暴力枚举查找
{
int Loc1 = Str[m].S.find(S);
reverse(Str[m].S.begin(),Str[m].S.end());
int Loc2 = Str[m].S.find(S);
if(Loc1<0&& Loc2<0) flag = 0;
}
int LENS = S.size();
if(flag) Max_Size = max(Max_Size,LENS); //更新长度
}
}
return Max_Size>=0?Max_Size:0; //防止没有公共串
}
int cmp(const void *a,const void *b)
{
return (*(String *)a).len - (*(String *)b).len;
}
int main(void)
{
// freopen("F:\\test.txt","r",stdin);
int T;scanf("%d",&T);
for(int t=1,n;t<=T&&scanf("%d",&n);++t)
{
for(int i=1;i<=n;++i)
{
char temp[MAXLen];
scanf("%s",temp); //定义结构体 内存放Str和它的长度,便于排序
Str[i].S = temp;
Str[i].len = Str[i].S.size();
}
qsort(Str+1,n,sizeof Str[0],cmp); //找出最小的边
printf("%d\n",Cal(n));
}
}