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

动态规划求解最长公共子序列

时间:2015-04-07 21:31:26      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream>
using namespace std;
void Print_LCS(int **b, string X, int i, int j)
{
    if (i == 0 || j == 0)
        return;
    if (b[i][j] == 1)
    {
        Print_LCS(b, X, i - 1, j - 1);
        cout << X.at(i) << "  ";
    }
    else if (b[i][j] == 0)
    {
        Print_LCS(b, X, i - 1, j);
    }
    else
    {
        Print_LCS(b, X, i, j - 1);
    }

}
void LCS_length(string X, string Y)
{
    int m = X.length();
    int n = Y.length();
    X = "0" + X;
    Y = "0" + Y;
    int **b = new int*[m + 1];
    for (int i = 0; i < m + 1; i++)
    {
        b[i] = new int[n + 1];
    }
    int **c = new int*[m+1];//LCS的长度
    for (int i = 0; i <=m; i++)
    {
        c[i] = new int[n+1];
    }
    for (int i = 1; i <= m; i++)
    {
        c[i][0] = 0;
    }
    for (int j = 0; j <= n; j++)
    {
        c[0][j] = 0;
    }
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (X.at(i) == Y.at(j))
            {
                c[i][j] = c[i - 1][j - 1] + 1;
                b[i][j] = 1;
            }
            else if (c[i - 1][j] >= c[i][j - 1])
            {
                c[i][j] = c[i - 1][j];
                b[i][j] = 0;
            }
            else
            {
                c[i][j] = c[i][j - 1];
                b[i][j] = -1;
            }

        }
    }
    Print_LCS(b,X,m,n);
    cout << "\n";
}

int main()
{
    string X= "ABCBDAB";
    string Y = "BDCABA";
    LCS_length(X,Y);

}

 

动态规划求解最长公共子序列

标签:

原文地址:http://www.cnblogs.com/liuhg/p/LCS.html

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