動態規劃-最長公共子字符串(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;    

}

後記

如果有不對的地方,望看過的各位指正。

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