现在的位置: 首页 > 综合 > 正文

HDU 1238 Substrings 【c++ string】

2018年05月02日 ⁄ 综合 ⁄ 共 1507字 ⁄ 字号 评论关闭

Substrings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7450    Accepted Submission(s): 3361

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
 
/*
题目大意:求出n个字符串的最长公共子序列,字符串可反转。
题解:先找出最短的字符串,然后在最短字符串中找子串。
如果子串或子串的反转为所有字符串的子串,将子串长度记录下来。
依此......求得所有子串长度中的最大者,即为最长公共子串。   
*/

思考:题目中用到很多C++中处理字符串的函数,使解题变得简单。

#include<cstdio>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
#define inf 110
int main()
{
    int T,n,i,j,k,mpos,mlen,max;
    string s[110];
    scanf("%d",&T);
    while(T--)
    {
        mlen=inf;
        max=0;
        scanf("%d",&n);
        for(i=0; i<n; i++)//找最短的字符串 
        {
            cin>>s[i];
            if(mlen>s[i].size())
            {
                mpos=i;
                mlen=s[i].size();
            }
        }
        for(i=mlen; i>=1; i--)//从最短的字符串中找子串
        {
             for(j=0; j<mlen-i+1; j++)
             {
                string s1,s2;
                s1=s[mpos].substr(j,i);//取最短字符串的子串 
                s2=s1;
                reverse(s2.begin(),s2.end());//将子串反转 
                for(k=0; k<n; k++)
                {
                    if(s[k].find(s1)==-1&&s[k].find(s2)==-1)
                    {
                        break;
                    }
                }
                if(k==n&&s1.size()>max)
                {
                    max=s1.size();
                }
            }
        }
        printf("%d\n",max);
    }
    return 0;
}

抱歉!评论已关闭.