码迷,mamicode.com
首页 > 其他好文 > 详细

poj 1458 最长公共子序列

时间:2018-02-05 00:21:25      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:color   ace   class   pac   nbsp   math   ret   ==   图片   

技术分享图片

题意:求两个字符串的最长公共子序列的长度

解题思路:

状态方程:

if(i == 0 || j == 0) dp[i,j] = 0

else if(X[i] == Y[j]) dp[i,j] = dp[i-1,j-1] + 1

else dp[i,j] = max(dp[i-1,j],dp[i,j-1])

#include<iostream>
#include<string>
#include<cmath>
using namespace std;

const int MAXN = 500;
int dp[MAXN][MAXN] = {0};//某子串长度为0的情况就包括在内;

int main()
{
    string str1,str2;
    int len1,len2;
    while(cin>>str1>>str2)
    {
        len1 = str1.length();
        len2 = str2.length();
        for(int i = 1;i<=len1;i++)
            for(int j = 1;j<=len2;j++)
            {
                if(str1[i-1] == str2[j-1])
                    dp[i][j] = dp[i-1][j-1] + 1;
                else
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
            }
        cout<<dp[len1][len2]<<endl;
    }
    return 0;
}

 

poj 1458 最长公共子序列

标签:color   ace   class   pac   nbsp   math   ret   ==   图片   

原文地址:https://www.cnblogs.com/ZZUGPY/p/8414534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!