最长公共子序列(动态规划)

题目:(POJ1458)

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > 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.

输入:

abcfbc         abfcab
programming    contest 
abcd           mnp

输出:

4
2
0

思路:

两个字符串s1,s2,用MaxLen(i,j)表示s1从左边开始i个字符与s2从左边开始j个字符形成的最大公共子序列的长度(i,j = 0,1,2,3,...)。所以这道题要求的就是MaxLen(sl的长度,s2的长度)。初始状态为i 或者j 等于0时,MaxLen等于0.

递推公式如下:


if(s[i-1] == s[j-1])
MaxLen(i,j) = MaxLen(i-1,j-1) + 1;
esle
MaxLen(i,j) = max(MaxLen(i-1,j),MaxLen(i,j-1));

如果s1[i-1]和s2[j-1]相等,那么在原来的最大长度的基础上加1.(这里要注意,比较的是s1[i-1]和s2[j-1],而不是s1[i]和s2[j]。因为i和j 表示的是长度,就像一个数组长度为n,那么它的最后一个元素下标是n-1.)

如果最后一个元素不相等,那么就要考虑两种情况中的最大。

代码:

#include <iostream>

using namespace std;
string s1;
string s2;
int MaxLen[1000][1000];
int main()
{
   while(cin >> s1 >>s2)
     {
    //MaxLen[i][j]表示s1左边i个字符与s2左边j个字符形成的最长公共子序列的长度

    int len1 = s1.length();
    int len2 = s2.length();
    //要求MaxLen[len1-1][len2-1];
     //初始状态
    for(int i = 0;i <= len1;i++)
        MaxLen[i][0] = 0;
    for(int j = 0;j <= len2;j++)
        MaxLen[0][j] = 0;
    //递推,从一个字符到整个长度
    for(int i = 1;i <= len1;i++)
    {
        for(int j = 1;j <=len2;j++)
        {
            if(s1[i-1] == s2[j-1])
               MaxLen[i][j] = MaxLen[i-1][j-1]+1;
            else
                MaxLen[i][j] = max(MaxLen[i-1][j],MaxLen[i][j-1]);
        }
    }
    cout << MaxLen[len1][len2] << "\n";
     }
    return 0;
}

要点:

由于设的MaxLen(i,j)中的参数是长度,而S中的索引是从0开始的,所以在s中索引时要-1.如s[i-1][j-1],最后求的是MaxLen(len1,len2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值