您的位置:首页 > 其它

DP之最长公共子序列 LCS

2016-02-07 16:41 423 查看
/*

DP之最长公共子序列 LCS

dp[0][j] (0<=j<=m)=0;

dp[i][0] (0<=i<=n)=0;

dp[i][j] = dp[i-1][j-1]+1;(s1[i] == s2[j])

dp[i][j] = max{dp[i-1][j],dp[i][j-1]} (s1[i] != s2[j])

题目1042:Coincidence

题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:

abcd

cxbydz

样例输出:

2

*/

#include <stdio.h>

#include <string.h>

int dp[101][101];

int max(int a, int b){return a>b ? a : b;}//取最大值函数

int main(){
int i,j;
char s1[101],s2[101];
while(scanf("%s%s",s1,s2) != EOF){//输入
int l1 = strlen(s1);
int l2 = strlen(s2);//依次求得两个字符串的长度
for(i=0;i<=l1;i++) dp[i][0] = 0;
for(j=0;j<=l2;j++) dp[0][j] = 0;//初始值
for(i=1;i<=l1;i++){
for(j=1;j<=l2;j++){//二重循环依次求得每个dp[i][j]值
if(s1[i-1] != s2[j-1])//因为字符串数组下标从0开始,所以第
//i个字符位置为s1[i-1],若当前两个字符不相等
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
//dp[i][j]为dp[i][j-1]和dp[i-1][j]中较大的一个
else dp[i][j] = dp[i-1][j-1]+1;
//若它们相等,则dp[i][j]比dp[i-1][j-1]再加1
}
}
printf("%d\n",dp[l1][l2]);
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: