您的位置:首页 > 其它

0011算法笔记——【动态规划】最长公共子序列问题(LCS)

2013-10-30 17:49 585 查看
     问题描述:一个给定序列的子序列是在该序列中删去若干元素后得到的序列。确切地说,若给定序列X= {
x1, x2,…, xm},则另一序列Z= {z1,
z2,…, zk}是X的子序列是指存在一个严格递增的下标序列 {i1, i2,…,
ik},使得对于所有j=1,2,…,k有 Xij=Zj。例如,序列Z={B,C,D,B}是序列X={A,B,C,B,D,A,B}的子序列,相应的递增下标序列为{2,3,5,7}。给定两个序列X和Y,当另一序列Z既是X的子序列又是Y的子序列时,称Z是序列X和Y的公共子序列。例如,若X= {
A, B, C, B, D, A, B}和Y= {B, D, C, A, B, A},则序列{B,C,A}是X和Y的一个公共子序列,序列{B,C,B,A}也是X和Y的一个公共子序列。而且,后者是X和Y的一个最长公共子序列,因为X和Y没有长度大于4的公共子序列。给定两个序列X= {x1, x2, …, xm}和Y= {y1,
y2, … , yn},要求找出X和Y的一个最长公共子序列。

     问题解析:设X= { A, B, C, B, D, A, B},Y=
{B, D, C, A, B, A}。求X,Y的最长公共子序列最容易想到的方法是穷举法。对X的多有子序列,检查它是否也是Y的子序列,从而确定它是否为X和Y的公共子序列。由集合的性质知,元素为m的集合共有2^m个不同子序列,因此,穷举法需要指数级别的运算时间。进一步分解问题特性,最长公共子序列问题实际上具有最优子结构性质。

      设序列X={x1,x2,……xm}和Y={y1,y2,……yn}的最长公共子序列为Z={z1,z2,……zk}。则有:

      (1)若xm=yn,则zk=xm=yn,且zk-1是Xm-1和Yn-1的最长公共子序列。

      (2)若xm!=yn且zk!=xm,则Z是Xm-1和Y的最长公共子序列。

      (3)若xm!=yn且zk!=yn,则Z是X和Yn-1的最长公共子序列。

      其中,Xm-1={x1,x2……xm-1},Yn-1={y1,y2……yn-1},Zk-1={z1,z2……zk-1}。

     递推关系:用c[i][j]记录序列Xi和Yj的最长公共子序列的长度。其中,Xi={x1,x2……xi},Yj={y1,y2……yj}。当i=0或j=0时,空序列是xi和yj的最长公共子序列。此时,c[i][j]=0;当i,j>0,xi=yj时,c[i][j]=c[i-1][j-1]+1;当i,j>0,xi!=yj时,

c[i][j]=max{c[i][j-1],c[i-1][j]},由此建立递推关系如下:



          构造最优解:由以上分析可知,要找出X={x1,x2,……xm}和Y={y1,y2,……yn}的最长公共子序列,可以按一下方式递归进行:当xm=yn时,找出xm-1和yn-1的最长公共子序列,然后在尾部加上xm(=yn)即可得X和Y的最长公共子序列。当Xm!=Yn时,必须解两个子问题,即找出Xm-1和Y的一个最长公共子序列及X和Yn-1的一个最长公共子序列。这两个公共子序列中较长者为X和Y的最长公共子序列。设数组b[i][j]记录c[i][j]的值由哪一个子问题的解得到的,从b[m]
开始,依其值在数组b中搜索,当b[i][j]=1时,表示Xi和Yj的最长公共子序列是由Xi-1和Yj-1的最长公共子序列在尾部加上xi所得到的子序列。当b[i][j]=2时,表示Xi和Yj的最长公共子序列与Xi-1和Yj-1的最长公共子序列相同。当b[i][j]=3时,表示Xi和Yj的最长公共子序列与Xi和Yj-1的最长公共子序列相同。
     代码如下:

[cpp]
view plaincopyprint?

//3d3-1 最长公共子序列问题   
#include "stdafx.h"   
#include <iostream> 
  
using namespace std;   
  
const int M = 7;  
const int N = 6;  
  
void output(char *s,int n);  
void LCSLength(int m,int n,char *x,char *y,int **c,int **b);  
void LCS(int i,int j,char *x,int **b);  
  
int main()  
{  
    //X={A,B,C,B,D,A,B}
  
    //Y={B,D,C,A,B,A}   
    char x[] = {' ','A','B','C','B','D','A','B'};  
    char y[] = {' ','B','D','C','A','B','A'};  
  
    int **c = new int *[M+1];  
    int **b = new int *[M+1];  
    for(int i=0;i<=M;i++)    
    {    
        c[i] = new int[N+1];  
        b[i] = new int[N+1];  
    }   
      
    cout<<"序列X:"<<endl;  
    output(x,M);  
    cout<<"序列Y:"<<endl;  
    output(y,N);  
  
    LCSLength(M,N,x,y,c,b);  
  
    cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;  
    cout<<"序列X、Y最长公共子序列为:"<<endl;  
    LCS(M,N,x,b);  
    cout<<endl;  
}  
  
void output(char *s,int n)  
{  
    for(int i=1; i<=n; i++)  
    {  
        cout<<s[i]<<" ";  
    }  
    cout<<endl;  
}  
  
void LCSLength(int m,int n,char *x,char *y,int **c,int **b)  
{  
    int i,j;  
  
    for(i=1; i<=m; i++)  
        c[i][0] = 0;  
    for(i=1; i<=n; i++)  
        c[0][i] = 0;  
  
    for(i=1; i<=m; i++)  
    {  
        for(j=1; j<=n; j++)  
        {  
            if(x[i]==y[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]=2;  
            }  
            else  
            {  
                 c[i][j]=c[i][j-1];  
                 b[i][j]=3;  
            }  
        }  
    }  
}  
  
void LCS(int i,int j,char *x,int **b)  
{  
    if(i==0 || j==0)  
    {  
        return;  
    }  
    if(b[i][j]==1)  
    {  
        LCS(i-1,j-1,x,b);  
        cout<<x[i]<<" ";  
    }  
    else if(b[i][j]==2)  
    {  
        LCS(i-1,j,x,b);  
    }  
    else  
    {  
        LCS(i,j-1,x,b);  
    }  
}  

//3d3-1 最长公共子序列问题
#include "stdafx.h"
#include <iostream>
using namespace std;

const int M = 7;
const int N = 6;

void output(char *s,int n);
void LCSLength(int m,int n,char *x,char *y,int **c,int **b);
void LCS(int i,int j,char *x,int **b);

int main()
{
//X={A,B,C,B,D,A,B}
//Y={B,D,C,A,B,A}
char x[] = {' ','A','B','C','B','D','A','B'};
char y[] = {' ','B','D','C','A','B','A'};

int **c = new int *[M+1];
int **b = new int *[M+1];
for(int i=0;i<=M;i++)
{
c[i] = new int[N+1];
b[i] = new int[N+1];
}

cout<<"序列X:"<<endl;
output(x,M);
cout<<"序列Y:"<<endl;
output(y,N);

LCSLength(M,N,x,y,c,b);

cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;
cout<<"序列X、Y最长公共子序列为:"<<endl;
LCS(M,N,x,b);
cout<<endl;
}

void output(char *s,int n)
{
for(int i=1; i<=n; i++)
{
cout<<s[i]<<" ";
}
cout<<endl;
}

void LCSLength(int m,int n,char *x,char *y,int **c,int **b)
{
int i,j;

for(i=1; i<=m; i++)
c[i][0] = 0;
for(i=1; i<=n; i++)
c[0][i] = 0;

for(i=1; i<=m; i++)
{
for(j=1; j<=n; j++)
{
if(x[i]==y[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]=2;
}
else
{
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
}
}

void LCS(int i,int j,char *x,int **b)
{
if(i==0 || j==0)
{
return;
}
if(b[i][j]==1)
{
LCS(i-1,j-1,x,b);
cout<<x[i]<<" ";
}
else if(b[i][j]==2)
{
LCS(i-1,j,x,b);
}
else
{
LCS(i,j-1,x,b);
}
}

            LCSLength函数在计算最优值时,分别迭代X,Y构造数组b,c。设数组每个元素单元计算耗费时间O(1),则易得算法LCSLength的时间复杂度为O(mn)。在算法LCS中,依据数组b的值回溯构造最优解,每一次递归调用使i,或j减小1。从而算法的计算时间为O(m+n)。LCS的回溯构造最优解过程如下图所示:



 
           算法的改进:对于一个具体问题,按照一般的算法设计策略设计出的算法,往往在算法的时间和空间需求上还可以改进。这种改进,通常是利用具体问题的一些特殊性。例如,在算法LCS_length和LCS中,可进一步将数组b省去。事实上,数组元素c[i,j]的值仅由c[i-1][j-1],c[i-1][j]和c[i][j-1]三个值之一确定,而数组元素b[i][j]也只是用来指示c[i][j]究竟由哪个值确定。因此,在算法LCS中,我们可以不借助于数组b而借助于数组c本身临时判断c[i][j]的值是由c[i-1][j-1],c[i-1][j]和c[i][j-1]中哪一个数值元素所确定,代价是Ο(1)时间。既然b对于算法LCS不是必要的,那么算法LCS_length便不必保存它。这一来,可节省θ(mn)的空间,而LCS_length和LCS所需要的时间分别仍然是Ο(mn)和Ο(m+n)。另外,如果只需要计算最长公共子序列的长度,则算法的空间需求还可大大减少。事实上,在计算c[i][j]时,只用到数组c的第i行和第i-1行。因此,只要用2行的数组空间就可以计算出最长公共子序列的长度。更进一步的分析还可将空间需求减至min(m,
n)。

[cpp]
view plaincopyprint?

//3d3-2 最长公共子序列问题   
#include "stdafx.h"   
#include <iostream> 
  
using namespace std;   
  
const int M = 7;  
const int N = 6;  
  
void output(char *s,int n);  
void LCSLength(int m,int n,char *x,char *y,int **c);  
void LCS(int i,int j,char *x,int **c);  
  
int main()  
{  
    //X={A,B,C,B,D,A,B}
  
    //Y={B,D,C,A,B,A}   
    char x[] = {' ','A','B','C','B','D','A','B'};  
    char y[] = {' ','B','D','C','A','B','A'};  
  
    int **c = new int *[M+1];  
    for(int i=0;i<=M;i++)    
    {    
        c[i] = new int[N+1];  
    }   
      
    cout<<"序列X:"<<endl;  
    output(x,M);  
    cout<<"序列Y:"<<endl;  
    output(y,N);  
  
    LCSLength(M,N,x,y,c);  
  
    cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;  
    cout<<"序列X、Y最长公共子序列为:"<<endl;  
    LCS(M,N,x,c);  
    cout<<endl;  
}  
  
void output(char *s,int n)  
{  
    for(int i=1; i<=n; i++)  
    {  
        cout<<s[i]<<" ";  
    }  
    cout<<endl;  
}  
  
void LCSLength(int m,int n,char *x,char *y,int **c)  
{  
    int i,j;  
  
    for(i=1; i<=m; i++)  
        c[i][0] = 0;  
    for(i=1; i<=n; i++)  
        c[0][i] = 0;  
  
    for(i=1; i<=m; i++)  
    {  
        for(j=1; j<=n; j++)  
        {  
            if(x[i]==y[j])  
            {  
                c[i][j]=c[i-1][j-1]+1;  
            }  
            else if(c[i-1][j]>=c[i][j-1])  
            {  
                c[i][j]=c[i-1][j];  
            }  
            else  
            {  
                 c[i][j]=c[i][j-1];  
            }  
        }  
    }  
}  
  
void LCS(int i,int j,char *x,int **c)  
{  
    if(i==0 || j==0)  
    {  
        return;  
    }  
    if(c[i][j]==c[i-1][j-1]+1)  
    {  
        LCS(i-1,j-1,x,c);  
        cout<<x[i]<<" ";  
    }  
    else if(c[i-1][j]>=c[i][j-1])  
    {  
        LCS(i-1,j,x,c);  
    }  
    else  
    {  
        LCS(i,j-1,x,c);  
    }  
}  

//3d3-2 最长公共子序列问题
#include "stdafx.h"
#include <iostream>
using namespace std;

const int M = 7;
const int N = 6;

void output(char *s,int n);
void LCSLength(int m,int n,char *x,char *y,int **c);
void LCS(int i,int j,char *x,int **c);

int main()
{
//X={A,B,C,B,D,A,B}
//Y={B,D,C,A,B,A}
char x[] = {' ','A','B','C','B','D','A','B'};
char y[] = {' ','B','D','C','A','B','A'};

int **c = new int *[M+1];
for(int i=0;i<=M;i++)
{
c[i] = new int[N+1];
}

cout<<"序列X:"<<endl;
output(x,M);
cout<<"序列Y:"<<endl;
output(y,N);

LCSLength(M,N,x,y,c);

cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;
cout<<"序列X、Y最长公共子序列为:"<<endl;
LCS(M,N,x,c);
cout<<endl;
}

void output(char *s,int n)
{
for(int i=1; i<=n; i++)
{
cout<<s[i]<<" ";
}
cout<<endl;
}

void LCSLength(int m,int n,char *x,char *y,int **c)
{
int i,j;

for(i=1; i<=m; i++)
c[i][0] = 0;
for(i=1; i<=n; i++)
c[0][i] = 0;

for(i=1; i<=m; i++)
{
for(j=1; j<=n; j++)
{
if(x[i]==y[j])
{
c[i][j]=c[i-1][j-1]+1;
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
}
else
{
c[i][j]=c[i][j-1];
}
}
}
}

void LCS(int i,int j,char *x,int **c)
{
if(i==0 || j==0)
{
return;
}
if(c[i][j]==c[i-1][j-1]+1)
{
LCS(i-1,j-1,x,c);
cout<<x[i]<<" ";
}
else if(c[i-1][j]>=c[i][j-1])
{
LCS(i-1,j,x,c);
}
else
{
LCS(i,j-1,x,c);
}
}

         运行结果如下:


       

       从运行结果中可以看出,算法LCS回溯算法仅仅打印了其中一条最大公共子序列,如果存在多条公共子序列的情况下。怎么解决?对b[i][j]二维数组的取值添加一种可能,等于4,这代表了我们说的这种多支情况,那么回溯的时候可以根据这个信息打印更多可能的选择。你从(7,6)点开始按b[i][j]的值指示的方向回溯,把所有的路径遍历一遍,如果是能达到起点(1,1)的路径,就是LCS了,有多少条打印多少条。可是,在回溯路径的时候,如果采用一般的全搜索,会进行了很多无用功。即重复了很多,且会遍历了一些无效路径,因为这些路径最终不会到达终点(1,1),因此加大算法复杂度和时间消耗。

      博文《求所有最大公共子序列的算法实现》给出了一种"矩行搜索"的解决办法降低了算法的复杂度。算法主要是利用两个栈store,print,一个用来储存节点,一个用来打印节点。

      栈的实现代码如下(文件Stack.h):

[cpp]
view plaincopyprint?

/**  
  头文件------head file  
 */    
  
template <class T>  
class StackNode{  
    public:  
        T data;  
        StackNode *next;  
};  
  
template <class T>  
class Stack{  
    public:  
        Stack(void):top(NULL){}  
        bool IsEmpty(void) const{ return top==NULL;}  
        void Push(const T data);  
        bool Pop(T *data);  
        bool Peek(T *data) const;  
        StackNode<T> * GetStackNode();  
    private:  
        StackNode<T> *top;  
};  
  
template <class T>  
StackNode<T> * Stack<T>::GetStackNode(){  
    return top;  
}  
  
template <class T>  
void Stack<T>::Push(const T data){  
    StackNode<T> *node = new StackNode<T>();  
    node->data = data;  
    node->next = top;  
    top = node;  
}  
  
template <class T>  
bool Stack<T>::Peek(T *data) const{  
    if(IsEmpty()) return false;  
    *data = top->data;  
    return true;  
}  
  
template <class T>  
bool Stack<T>::Pop(T *data){  
    if(IsEmpty()) return false;  
    *data = top->data;  
    StackNode<T> *node = top;  
    top = top->next;  
    delete(node);  
    return true;  
}  

/**
头文件------head file
*/

template <class T>
class StackNode{
public:
T data;
StackNode *next;
};

template <class T>
class Stack{
public:
Stack(void):top(NULL){}
bool IsEmpty(void) const{ return top==NULL;}
void Push(const T data);
bool Pop(T *data);
bool Peek(T *data) const;
StackNode<T> * GetStackNode();
private:
StackNode<T> *top;
};

template <class T>
StackNode<T> * Stack<T>::GetStackNode(){
return top;
}

template <class T>
void Stack<T>::Push(const T data){
StackNode<T> *node = new StackNode<T>();
node->data = data;
node->next = top;
top = node;
}

template <class T>
bool Stack<T>::Peek(T *data) const{
if(IsEmpty()) return false;
*data = top->data;
return true;
}

template <class T>
bool Stack<T>::Pop(T *data){
if(IsEmpty()) return false;
*data = top->data;
StackNode<T> *node = top;
top = top->next;
delete(node);
return true;
}

      所有最长公共子序列问题LCS 矩阵搜索代码如下:

[cpp]
view plaincopyprint?

//3d3-3 所有最长公共子序列问题LCS 矩阵搜索   
#include "stdafx.h"   
#include "stack.h"
  
#include <iostream>   
using namespace std;  
  
typedef int **Matrix;  
const int M = 7;  
const int N = 6;  
  
typedef struct _Element  
{  
    int lcslen;//当前节点的LCS长度  
    int row;//当前节点的行坐标  
    int col;//当前节点的列坐标  
}Element;  
  
void output(char *s,int n);  
  
Element CreateElement(int nlen, int row, int col);  
  
Matrix GreateMatrix(int row, int col);  
void DeleteMatrix(Matrix p, int row);  
  
void PrintStack(Stack<Element> *ps, char *str, int len);  
void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype);  
  
void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb);  
void LCS(char *x, Matrix pc, Matrix pb, int row, int col);//矩阵搜索回溯  
  
  
int main(){  
    char x[] = {' ','A','B','C','B','D','A','B'};  
    char y[] = {' ','B','D','C','A','B','A'};  
  
    Matrix b = GreateMatrix(M, N);  
    Matrix c = GreateMatrix(M, N);  
  
    LCSLength(M,N,x,y,c,b);  
  
    cout<<"序列X:"<<endl;  
    output(x,M);  
    cout<<"序列Y:"<<endl;  
    output(y,N);  
  
    cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;  
    cout<<"序列X、Y最长公共子序列为:"<<endl;  
  
    LCS(x,c,b,M,N);  
  
    DeleteMatrix(b,M);  
    DeleteMatrix(c,M);  
  
    return 0;  
}  
  
void output(char *s,int n)  
{  
    for(int i=1; i<=n; i++)  
    {  
        cout<<s[i]<<" ";  
    }  
    cout<<endl;  
}  
  
Element CreateElement(int nlen, int row, int col)  
{  
    Element ele;  
    ele.lcslen = nlen;  
    ele.col = col;  
    ele.row = row;  
    return ele;  
}  
  
Matrix GreateMatrix(int row, int col)  
{  
    Matrix p = new int *[row+1];  
    for(int i=0;i<=row;i++)    
    {    
        p[i] = new int[col+1];  
    }   
    return p;  
}  
  
void DeleteMatrix(Matrix p, int row)  
{  
    for(int i=0;i<=row;i++)    
    {    
        delete []p[i];  
    }  
  
    delete []p;  
}  
  
void PrintStack(Stack<Element> *s,char *str,int len)  
{  
    if(s == NULL || str == NULL)  
        return;  
      
    StackNode<Element> *sn = s->GetStackNode();  
  
    while(sn!=NULL && sn->data.row<=len)  
    {  
        cout<<str[sn->data.row]<<" ";  
        sn = sn->next;  
    }  
  
    cout<<endl;  
}  
  
void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype)  
{  
    switch(pb[curposx][curposy])  
    {  
    case 1:  
        eposx = curposx;  
        eposy = curposy;  
        return;  
    case 2:  
        SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);  
        break;  
    case 3:  
        SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);  
        break;  
    case 4:  
        if(ntype == 0)  
            //搜索e1点,如过碰到分叉点,向上继续搜索  
            SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);  
        else  
            //搜索e2点,如过碰到分叉点,向左继续搜索
  
            SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);  
        break;  
    }  
}  
  
void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb)  
{  
    int i,j;  
  
    for(i=1; i<=m; i++)  
        pc[i][0] = 0;  
    for(i=1; i<=n; i++)  
        pc[0][i] = 0;  
  
    for(i=1; i<=m; i++)  
    {  
        for(j=1; j<=n; j++)  
        {  
            if(x[i]==y[j])  
            {  
                pc[i][j]=pc[i-1][j-1]+1;  
                pb[i][j]=1;  
            }  
            else if(pc[i-1][j]>pc[i][j-1])  
            {  
                pc[i][j]=pc[i-1][j];  
                pb[i][j]=2;  
            }  
            else if(pc[i-1][j]<pc[i][j-1])  
            {  
                 pc[i][j]=pc[i][j-1];  
                 pb[i][j]=3;  
            }  
            else  
            {  
                pc[i][j] = pc[i][j-1];//由左节点或上节点转移而来  
                pb[i][j] = 4;//标记为4  
            }  
        }  
    }  
}  
  
void LCS(char *x, Matrix pc, Matrix pb, int row, int col)  
{  
    if(x == NULL || pc == NULL || pb == NULL)  
        return;  
      
    Stack<Element> store, print;//构造两个栈store,print  
    Element storetop;//store栈的栈顶节点  
    Element element;//临时变量   
    Element virtualnode;//虚拟节点  
    int ntoplen;//保存store栈顶节点的LCS长度  
    int ex1,ey1,ex2,ey2;//矩形搜索的两个节点的坐标  
    int i,j;  
  
    virtualnode = CreateElement(pc[row][col]+1, row+1, col+1);  
  
    store.Push(virtualnode);//压入虚拟节点到store  
  
    while(!store.IsEmpty())  
    {  
        store.Pop(&storetop);  
        if(storetop.row == 1 || storetop.col == 1)//如果是边界节点  
        {  
            print.Push(storetop);  
            PrintStack(&print, x, row);//打印print栈里面除虚拟节点之外的所有节点  
            store.Peek(&element);  
            ntoplen = element.lcslen;//当前store的栈顶节点的LCS长度  
  
            /**********弹出print栈中所有LCS长度小于等于ntoplen的节点**************/  
            while(print.Peek(&element) && element.lcslen<=ntoplen)  
            {  
                print.Pop(&element);  
            }  
        }  
        else  
        {  
            print.Push(storetop);  
            SearchE(pb, storetop.row-1, storetop.col-1, ex1, ey1, 0);  
            SearchE(pb, storetop.row-1, storetop.col-1, ex2, ey2, 1);/*also other value is ok*/  
  
            if(ex1 == ex2 && ey1 ==ey2)  
            {  
                element = CreateElement(pc[ex1][ey1], ex1, ey1);  
                store.Push(element);//压入store栈,回到步骤2  
            }  
            else  
            {  
                for(i=ex1; i<=ex2; i++)  
                    for(j=ey2; j<=ey1; j++)  
                    {  
                        if(pb[i][j] == 1)  
                        {  
                            element = CreateElement(pc[i][j], i, j);  
                            store.Push(element);  
                        }  
                    }  
            }  
        }  
  
    }  
}  

//3d3-3 所有最长公共子序列问题LCS 矩阵搜索
#include "stdafx.h"
#include "stack.h"
#include <iostream>
using namespace std;

typedef int **Matrix;
const int M = 7;
const int N = 6;

typedef struct _Element
{
int lcslen;//当前节点的LCS长度
int row;//当前节点的行坐标
int col;//当前节点的列坐标
}Element;

void output(char *s,int n);

Element CreateElement(int nlen, int row, int col);

Matrix GreateMatrix(int row, int col);
void DeleteMatrix(Matrix p, int row);

void PrintStack(Stack<Element> *ps, char *str, int len);
void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype);

void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb);
void LCS(char *x, Matrix pc, Matrix pb, int row, int col);//矩阵搜索回溯

int main(){
char x[] = {' ','A','B','C','B','D','A','B'};
char y[] = {' ','B','D','C','A','B','A'};

Matrix b = GreateMatrix(M, N);
Matrix c = GreateMatrix(M, N);

LCSLength(M,N,x,y,c,b);

cout<<"序列X:"<<endl;
output(x,M);
cout<<"序列Y:"<<endl;
output(y,N);

cout<<"序列X、Y最长公共子序列长度为:"<<c[M]
<<endl;
cout<<"序列X、Y最长公共子序列为:"<<endl;

LCS(x,c,b,M,N);

DeleteMatrix(b,M);
DeleteMatrix(c,M);

return 0;
}

void output(char *s,int n)
{
for(int i=1; i<=n; i++)
{
cout<<s[i]<<" ";
}
cout<<endl;
}

Element CreateElement(int nlen, int row, int col)
{
Element ele;
ele.lcslen = nlen;
ele.col = col;
ele.row = row;
return ele;
}

Matrix GreateMatrix(int row, int col)
{
Matrix p = new int *[row+1];
for(int i=0;i<=row;i++)
{
p[i] = new int[col+1];
}
return p;
}

void DeleteMatrix(Matrix p, int row)
{
for(int i=0;i<=row;i++)
{
delete []p[i];
}

delete []p;
}

void PrintStack(Stack<Element> *s,char *str,int len)
{
if(s == NULL || str == NULL)
return;

StackNode<Element> *sn = s->GetStackNode();

while(sn!=NULL && sn->data.row<=len)
{
cout<<str[sn->data.row]<<" ";
sn = sn->next;
}

cout<<endl;
}

void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype)
{
switch(pb[curposx][curposy])
{
case 1:
eposx = curposx;
eposy = curposy;
return;
case 2:
SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);
break;
case 3:
SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);
break;
case 4:
if(ntype == 0)
//搜索e1点,如过碰到分叉点,向上继续搜索
SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);
else
//搜索e2点,如过碰到分叉点,向左继续搜索
SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);
break;
}
}

void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb)
{
int i,j;

for(i=1; i<=m; i++)
pc[i][0] = 0;
for(i=1; i<=n; i++)
pc[0][i] = 0;

for(i=1; i<=m; i++)
{
for(j=1; j<=n; j++)
{
if(x[i]==y[j])
{
pc[i][j]=pc[i-1][j-1]+1;
pb[i][j]=1;
}
else if(pc[i-1][j]>pc[i][j-1])
{
pc[i][j]=pc[i-1][j];
pb[i][j]=2;
}
else if(pc[i-1][j]<pc[i][j-1])
{
pc[i][j]=pc[i][j-1];
pb[i][j]=3;
}
else
{
pc[i][j] = pc[i][j-1];//由左节点或上节点转移而来
pb[i][j] = 4;//标记为4
}
}
}
}

void LCS(char *x, Matrix pc, Matrix pb, int row, int col)
{
if(x == NULL || pc == NULL || pb == NULL)
return;

Stack<Element> store, print;//构造两个栈store,print
Element storetop;//store栈的栈顶节点
Element element;//临时变量
Element virtualnode;//虚拟节点
int ntoplen;//保存store栈顶节点的LCS长度
int ex1,ey1,ex2,ey2;//矩形搜索的两个节点的坐标
int i,j;

virtualnode = CreateElement(pc[row][col]+1, row+1, col+1);

store.Push(virtualnode);//压入虚拟节点到store

while(!store.IsEmpty())
{
store.Pop(&storetop);
if(storetop.row == 1 || storetop.col == 1)//如果是边界节点
{
print.Push(storetop);
PrintStack(&print, x, row);//打印print栈里面除虚拟节点之外的所有节点
store.Peek(&element);
ntoplen = element.lcslen;//当前store的栈顶节点的LCS长度

/**********弹出print栈中所有LCS长度小于等于ntoplen的节点**************/
while(print.Peek(&element) && element.lcslen<=ntoplen)
{
print.Pop(&element);
}
}
else
{
print.Push(storetop);
SearchE(pb, storetop.row-1, storetop.col-1, ex1, ey1, 0);
SearchE(pb, storetop.row-1, storetop.col-1, ex2, ey2, 1);/*also other value is ok*/

if(ex1 == ex2 && ey1 ==ey2)
{
element = CreateElement(pc[ex1][ey1], ex1, ey1);
store.Push(element);//压入store栈,回到步骤2
}
else
{
for(i=ex1; i<=ex2; i++)
for(j=ey2; j<=ey1; j++)
{
if(pb[i][j] == 1)
{
element = CreateElement(pc[i][j], i, j);
store.Push(element);
}
}
}
}

}
}

          矩形搜索LCS算法回溯路径如下:



     算法LCS先构造了一个虚拟节点virtualnode,指向节点(m,n)的右下角,即(m+1,n+1),这个节点的LCS的长度假设为最大公共子序列长度+1。将虚拟节点压入栈store,然后从虚拟节点出发,当状态b[i][j]=4时,节点开始分叉,根据设置类型向上(ntype=0)、向左(ntype=1)矩形搜索查找导致公共子序列长度发生变化的节点(跳跃点),即b[i][j]=1对应的节点压入store栈中,然后s判断store弹出元素是否已到达边界,如果没有到达,则将节点压入print栈中,如果到达边界,则打印print栈,输出其中一个最长公共序列。
运行结果如下:



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: