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

poj1458 Common Subsequence(经典DP)

时间:2014-11-08 23:39:50      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:dp   poj   

题目意思:

http://poj.org/problem?id=1458

给出两个字符串,求出这两个字符串的最长子序列的长度,最长子序列的定义如下:

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.

题目分析:

此题为《算法导论》上的DP一节的经典题目。这里只给出动态转移方程:dp[i][j]:表示字符串x和字符串y,x的长度为i和y的长度j的最长子序列。

                dp[i-1][j-1]+1      x[i]=y[j]

dp[i][j]={

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


AC代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int dp[1001][1001];
int DpCon(string s1,string s2){
    for(int i=1;i<=s1.size();i++){
        for(int j=1;j<=s2.size();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]);
        }
    }
    return dp[s1.size()][s2.size()];
}
int main()
{
    string s1,s2;
    while(cin>>s1>>s2){
       memset(dp,0,sizeof(dp));
       cout<<DpCon(s1,s2)<<endl;
    }
    return 0;
}

poj1458 Common Subsequence(经典DP)

标签:dp   poj   

原文地址:http://blog.csdn.net/fool_ran/article/details/40930301

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