Common Subsequence
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 37 Accepted Submission(s) : 28
Problem Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = another sequence Z = is a subsequence of X if there exists a strictly increasing sequence of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = is a subsequence of X = with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y. The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0
//title:Common Subsequence
//问题分类:动态规划--最长公共子序列LCM
//dp[i][j]表示s1以第i个字符结尾和s2以第j个字符结尾的最长的公共子串的长度
//当i=0或j=0时,dp[i][j]=0
//当s1[i-1]=s2[j-1]时,表示s1与s2相同,则dp[i][j]=dp[i-1][j-1]+1
//当s1[i-1]!=s2[j-1]时,表示s1与s2不相同,则dp[i][j]=max(dp[i-1][j]+1,dp[i][j-1]+1)
#include<stdio.h>
#include<string.h>
int max(int a,int b){
return a<b?b:a;
}
char s1[2000],s2[2000];
int dp[2000][2000];
int main(){
freopen("in.txt","r",stdin);
while(scanf("%s%s",s1,s2)!=EOF){
int a=strlen(s1);
int b=strlen(s2);
//初始化
for(int i=0;i<=a;i++){
dp[i][0]=0;
}
for(int i=0;i<=b;i++){
dp[0][i]=0;
}
//这里要从1开始,因为有i-1,j-1
//s的第n个字符实际下标是n-1
//因此判断 s1[i-1]==s2[j-1]
for(int i=1;i<=a;i++){
for(int j=1;j<=b;j++){
if(s1[i-1]==s2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
}else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
printf("%d\n",dp[a][b]);
}
return 0;
}