http://acm.hdu.edu.cn/showproblem.php?pid=4681
String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 939 Accepted Submission(s): 344
Problem Description
Given 3 strings A, B, C, find the longest string D which satisfy the following rules:
a) D is the subsequence of A
b) D is the subsequence of B
c) C is the substring of D
Substring here means a consecutive subsequnce.
You need to output the length of D.
Input
The first line of the input contains an integer T(T = 20) which means the number of test cases.
For each test case, the first line only contains string A, the second line only contains string B, and the third only contains string C.
The length of each string will not exceed 1000, and string C should always be the subsequence of string A and string B.
All the letters in each string are in lowercase.
Output
For each test case, output Case #a: b. Here a means the number of case, and b means the length of D.
Sample Input
2
aaaaa
aaaa
aa
abcdef
acebdf
cf
Sample Output
Case #1: 4
Case #2: 3
Hint
For test one, D is "aaaa", and for test two, D is "acf".
Source
2013 Multi-University Training Contest 8
Recommend
zhuyuanchen520
Statistic | Submit | Discuss | Note
解析:
题意:
给出a,b,c三组字符串,
求出a,b最长公共序列长度且这个序列必须包含有c作为它的子串
思路:
最长公共序列+枚举 ;
既然所求序列必须含有子串c,那么在计算时就必须考虑这一个因素
如何处理呢?
1.分别记录c在a,b,中完整出现的起止位置
2.正反方向求一遍a,b的最长公共序列长度
3.枚举a,b起止位置,求起止位置左右区间的最公共序列长度
再把结果加上c的长度即可
468MS 8896K 1766 B C++
*/
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <iostream>
using namespace std;
const int maxn=1000+50;
char s1[maxn],s2[maxn],s3[maxn];
int dp1[maxn][maxn],dp2[maxn][maxn];
int d1[maxn][3],d2[maxn][3];
int t1,t2;
int max(int a,int b)
{
return a>b? a:b;
}
void init()
{
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
memset(d1,-1,sizeof(d1));
memset(d2,-1,sizeof(d2));
}
void getst(char a[],char b[],int f)
{
int n,ns,i,j,t;
n=strlen(a);
ns=strlen(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[0])
continue;
for(j=0,t=i;t<n;t++)
{
if(a[t]==b[j])
{
j++;
if(j==ns)
break;
}
}
if(j==ns)
{
if(f==0)
{
d1[t1][0]=i;
d1[t1++][1]=t;
}
else
{d2[t2][0]=i;
d2[t2++][1]=t;
}
}
}
}
int main()
{
int T,i,j,n,ca=0;
int ans,n1,n2,n3;
scanf("%d",&T);
while(T--)
{ init();
scanf("%s",s1);
scanf("%s",s2);
scanf("%s",s3);
printf("Case #%d: ",++ca);
n1=strlen(s1);
n2=strlen(s2);
n3=strlen(s3);
for(i=1;i<=n1;i++)//正序
for(j=1;j<=n2;j++)
{
if(s1[i-1]==s2[j-1])
dp1[i][j]=dp1[i-1][j-1]+1;
else
dp1[i][j]=max(dp1[i-1][j],dp1[i][j-1]);
}
for(i=n1-1;i>=0;i--)//逆序
{
for(j=n2-1;j>=0;j--)
{
if(s1[i]==s2[j])
dp2[i][j]=dp2[i+1][j+1]+1;
else
dp2[i][j]=max(dp2[i][j+1],dp2[i+1][j]);
}
}
t1=t2=ans=0;
getst(s1,s3,0);
getst(s2,s3,1);
for(i=0;i<t1;i++)
for(j=0;j<t2;j++)
{
ans=max(ans,dp1[d1[i][0]][d2[j][0]]+dp2[d1[i][1]+1][d2[j][1]+1]);
}
ans=ans+n3;
printf("%d\n",ans);
}
return 0;
}