• 动态规划求最长公共子序列源程序


    参考算法导论,得出源程序如下:

    //
    //动态规划法求最长公共子序列,参考算法导论15.4
    //
    
    
    #include<iostream>
    #include <vector>
    
    using namespace std;
    
    void lcs_length(const vector<char>& X, const vector<char>& Y,
                    vector<vector<int> >& c, vector<vector<char> >& b)
                    //X[1..m],Y[1..n],c[0..m,0..n],b[1..m][1..n],故要经过相应的转换
    {
        int i=0,j=0;
        int m = X.size();
        int n = Y.size();
        for (i=1; i<=m; ++i)
            c[i][0] = 0;
        for (j=0; j<=n; ++j)
            c[0][j] = 0;
        for (i=1; i<=m; ++i)
            for (j=1; j<=n; ++j)
            {
                if (X[i-1] == Y[j-1])
                {
                    c[i][j] = c[i-1][j-1]+1;
                    b[i-1][j-1] = 'x';
                } 
                else if (c[i-1][j] >= c[i][j-1])
                {
                    c[i][j] = c[i-1][j];
                    b[i-1][j-1] = 'u';
                }
                else
                {
                    c[i][j] = c[i][j-1];
                    b[i-1][j-1] = 'l';
                }
            }
    }
    
    void print_lcs(const vector<vector<char> >& b, const vector<char> X, 
                   int i, int j)
    {
        if (-1==i ||0 ==-1)
            return;
        if ('x' == b[i][j])
        {
            print_lcs(b,X,i-1,j-1);
            cout << X[i];
        }
        else if ('u' == b[i][j])
            print_lcs(b,X,i-1,j);
        else
            print_lcs(b,X,i,j-1);
    
    }
    
    int main()
    {
        vector<char> X, Y;
        vector<vector<int> > c;
        vector<vector<char> >b; //注意,这里两个尖括号之间要有空格,不然会被认为是符号">>"
        int i=0, j=0, m=0, n=0;
        cin >> m >> n;
        X.resize(m);
        Y.resize(n);
        b.resize(m);
        c.resize(m+1);
        cout << "input the element of X" << endl;
        for (i=0; i<m; ++i)
        {
            cin >> X[i];
            b[i].resize(n);
            c[i].resize(n+1);
        }
        c[m].resize(n+1);
        cout << "input the element of Y" << endl;
        for (i=0; i<n; ++i)
            cin >> Y[i];
        lcs_length(X,Y,c,b);
        for (i=0; i<=m; ++i){
            for (j=0; j<=n; ++j)
                cout << c[i][j] <<' ';
            cout << endl;
        }
        cout << endl;
        for (i=0; i<m; ++i){
            for (j=0; j<n; ++j)
                cout << b[i][j] <<' ';
            cout << endl;
        }
        print_lcs(b,X,m-1,n-1);
        cout << endl;
        return 0;
    }
  • 相关阅读:
    网络编程初探
    MY GOAL
    推荐一个网站:编程资料网 http://www.ourdev.net/
    端午时节, 嘿嘿, 用论文砸自己一把
    Requirement for My Job
    MVC 才是正道, say bye to naive
    linux下的top命令参数说明 (virt,res,shr,data 的意义)
    Linux中线程与CPU核的绑定
    linux多线程域名解析函数导致的内存空间占用增长
    MD5简介
  • 原文地址:https://www.cnblogs.com/lyfruit/p/2831725.html
Copyright © 2020-2023  润新知