您的位置:首页 > 其它

HDU 1238 最长子串

2016-07-18 17:12 204 查看
Substrings
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d
& %I64u 
HDU
1238

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个串的最长子串(串可以翻转)

奇怪的是我按照最长子串做是错的

网上都是拿暴力过的

WA:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;

bool com(string x,string y){
return x.size()<y.size();
}
int lcs(string x,string y){
int dp[105][105]={0},len1=x.size(),len2=y.size(),ans=0;
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++)
if(x[i-1]==y[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=0;
ans=max(*max_element(dp[i],dp[i]+len2+1),ans);
}
return ans;
}
int main()
{
std::cout.sync_with_stdio(false);
int t,n;
string str[105];
while(cin>>t){
while(t--){
cin>>n;
for(int i=0;i<n;i++)
cin>>str[i];
sort(str,str+n,com);
int ans=999;
for(int i=1;i<n;i++){
int ans1=lcs(str[0],str[i]);
reverse(str[i].begin(),str[i].end());
int ans2=lcs(str[0],str[i]);
ans1=max(ans1,ans2);
ans=min(ans1,ans);

}
cout<<ans<<endl;
}

}
}
AC(别人的):

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int t, n, i, j, k;
string s[102];
int sm, mlen = 200, max;
cin >> t;
while(t--)
{
cin >> n;
for(i = 0; i < n; i++)
{
cin >> s[i];
if(mlen > s[i].size())
{
sm = i;
mlen = s[i].size();
}
}
max = 0;
for(i = s[sm].size(); i > 0; i--)
for(j = 0; j < s[sm].size() - i + 1; j++)
{
string s1, s2;
s1 = s[sm].substr(j, i);
s2 = s1;
reverse(s2.begin(), s2.end());
for(k = 0; k < n; k++)
if(s[k].find(s1, 0) == -1 && s[k].find(s2, 0))
break;

if(k == n && max < s1.size())
max = s1.size();
}
cout << max << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: