hdu 4681 String
String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1162 Accepted Submission(s): 426
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
//578MS 16064K 2186 B C++ /* DP,最长公共子序列小变形 dp[i][j] 代表a[]前i个字符和b[]前j个字符最长公共子序列 dp3[i][j] 代表a[]后i个字符和b[]后j个字符最长公共子序列 dp1[i][j]代表c[]前j个字符和a[]前i个字符匹配,最后的匹配初始 位置,-1表示不能匹配 dp2[i][j]同理 */ #include<stdio.h> #include<string.h> #define N 1005 int dp[N][N]; int dp1[N][N]; int dp2[N][N]; int dp3[N][N]; char a[N],b[N],c[N]; int Max(int a,int b) { return a>b?a:b; } int main(void) { int t; int k=1; scanf("%d",&t); while(t--) { scanf("%s%s%s",a,b,c); int la=strlen(a); int lb=strlen(b); int lc=strlen(c); memset(dp,0,sizeof(dp)); memset(dp3,0,sizeof(dp3)); for(int i=1;i<=la;i++) //a、b前匹配 for(int j=1;j<=lb;j++){ if(a[i-1]==b[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=Max(dp[i][j-1],dp[i-1][j]); } for(int i=1;i<=la;i++) //a、b后匹配 for(int j=1;j<=lb;j++){ if(a[la-i]==b[lb-j]) dp3[i][j]=dp3[i-1][j-1]+1; else dp3[i][j]=Max(dp3[i][j-1],dp3[i-1][j]); } /* for(int i=1;i<=la;i++){ for(int j=1;j<=lb;j++) printf("%d ",dp3[i][j]); printf("\n"); } */ for(int i=1;i<=lc;i++) dp1[0][i]=-1; for(int i=0;i<=la;i++) dp1[i][0]=i; for(int i=1;i<=la;i++) //求起始位置 for(int j=1;j<=lc;j++){ if(a[i-1]==c[j-1]) dp1[i][j]=dp1[i-1][j-1]; else dp1[i][j]=dp1[i-1][j]; } for(int i=1;i<=lc;i++) dp2[0][i]=-1; for(int i=0;i<=lb;i++) dp2[i][0]=i; for(int i=1;i<=lb;i++) for(int j=1;j<=lc;j++){ if(b[i-1]==c[j-1]) dp2[i][j]=dp2[i-1][j-1]; else dp2[i][j]=dp2[i-1][j]; } /* for(int i=1;i<=la;i++){ for(int j=1;j<=lc;j++) printf("%d ",dp1[i][j]); printf("\n"); } */ int maxn=0; for(int i=0;i<=la;i++) //枚举求最优 for(int j=0;j<=lb;j++){ int t1=dp1[la-i][lc]; int t2=dp2[lb-j][lc]; if(t1==-1 || t2==-1) continue; maxn=Max(maxn,dp3[i][j]+dp[t1][t2]); } printf("Case #%d: %d\n",k++,maxn+lc); } return 0; }