hdu 1238 暴力枚举+STL

来源:互联网 发布:互助盘 资金匹配算法 编辑:程序博客网 时间:2024/06/17 12:26

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

题解:

暴力枚举所有的子串。注意从长度最长的开始枚举,遇到一个匹配的就退出循环。这里没注意到所有子串不匹配的情况,输出0。wa了一次。
注意STL的find函数没有找到是返回一个很大的值。

代码:

#include <bits/stdc++.h>using namespace std;vector<string> vec;bool cmp(string a,string b){    return a.length()<b.length();}bool judge(string str){    int len = str.length();    int siz = vec.size();    int count=0;    string rev;    for(int i=len-1;i>=0;i--)    {        rev+=str[i];    }    for(int i=1;i<siz;i++)    {        if(vec[i].find(str)<=100)            count++;        else if(vec[i].find(rev)<=100)        {            count++;        }    }    //cout<<count<<endl;    if(count==siz-1) return true;    else return false;}int main(){    int T;    scanf("%d",&T);    int n;    while(T--)    {       int ans=0;       scanf("%d",&n);       string tmp;       for(int i=0;i<n;i++)       {           cin>>tmp;           vec.push_back(tmp);       }       sort(vec.begin(),vec.end(),cmp);       tmp=vec[0];       int len = tmp.length();       string str;       bool flag=0;       for(int i=4;i>=1;i--)         {           for(int j=0;j<len;j++)           {               str="";              for(int k=0;k<i&&j+k<len;k++)             {                str+=tmp[j+k];             }             if(str.length()==i)             {                 if(judge(str))                 {                    ans = str.length();                    flag=1;                    break;                 }             }           }           if(flag==1) break;         }       cout<<ans<<endl;       vec.clear();    }    return 0;}
原创粉丝点击