HDU 1238 Substrings 字符串水題,STL String 的應用

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));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章