动态规划-最长公共子字符串(LCS)

背景

学习算法导论,看到动态规划的LCS,于是用C++将算法实现。

原理

原理网上博客太多了,这里就不再细讲,可以参看July的博客:
http://blog.csdn.net/v_july_v/article/details/6695482

注意

编程实现的过程中要特别注意边界条件和算法导论书上的实现有出入的地方,否则会出现数组越界LCS统计不完整的问题。

代码


/***************************************************
* Author: R9barcelona
* Description:
***************************************************/

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

int b[100][100];

//计算LCS的长度
template <class T>
void LCS(T X[], T Y[])
{
    int m = strlen(X);
    int n = strlen(Y);
    cout << "length-X:" << m << " length-Y:" << n << endl;
    int c[m+1][n+1];

    for(int i = 1; i < m+1; i++) //m个数
        c[i][0] = 0;
    for(int j = 0; j < n+1; j++) //n+1个数
        c[0][j] = 0;

    for(int i = 0; i < m; i++)
        for(int j = 0; j < n ; j++)
        {
            if(X[i] == Y[j])
            {
                c[i+1][j+1] = c[i][j] + 1;
                b[i][j] = 2;//"upleft";       
            }
            else if(c[i][j+1] >= c[i+1][j])
            {
                c[i+1][j+1] = c[i][j+1];
                b[i][j] = 4;//"up";       
            }
            else
            {
                c[i+1][j+1] = c[i+1][j];
                b[i][j] = 6;//"left";       
            }
        }
   // return b;          

}

//构造LCS
template <class T>
int print_lcs(T X[], int i, int j)
{
    if(i == -1 || j == -1)
        return 0;
    if(b[i][j] == 2)//upleft
    {
        print_lcs(X, i-1, j-1);
        cout << X[i] << " ";
    }
    else if(b[i][j] == 4)//up
        print_lcs(X, i-1, j);
    else//left
        print_lcs(X, i, j-1);
}

int main()
{
    char X[] = {'A','B','C','B','D','A','B'};
    char Y[] = {'A','B','D','C','A','B','A'};
    LCS(X,Y);
    /*
    for(int i = 0; i < 7; i++)
    {
        for(int j = 0; j < 6; j++)
        {
            cout << b[i][j] << " ";    
        }
        cout << endl;
    }
    */
    print_lcs(X,strlen(X)-1,strlen(Y)-1);   
    cout << endl;   

    return 0;    

}

后记

如果有不对的地方,望看过的各位指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章