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

问题描述:一个给定序列的子序列是在该序列中删去若干元素后得到的序列。确切地说,若给定序列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][n]开始,依其值在数组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 plain  copy
  1. //3d3-1 最长公共子序列问题  
  2. #include "stdafx.h"  
  3. #include <iostream>   
  4. using namespace std;   
  5.   
  6. const int M = 7;  
  7. const int N = 6;  
  8.   
  9. void output(char *s,int n);  
  10. void LCSLength(int m,int n,char *x,char *y,int **c,int **b);  
  11. void LCS(int i,int j,char *x,int **b);  
  12.   
  13. int main()  
  14. {  
  15.     //X={A,B,C,B,D,A,B}  
  16.     //Y={B,D,C,A,B,A}  
  17.     char x[] = {' ','A','B','C','B','D','A','B'};  
  18.     char y[] = {' ','B','D','C','A','B','A'};  
  19.   
  20.     int **c = new int *[M+1];  
  21.     int **b = new int *[M+1];  
  22.     for(int i=0;i<=M;i++)    
  23.     {    
  24.         c[i] = new int[N+1];  
  25.         b[i] = new int[N+1];  
  26.     }   
  27.       
  28.     cout<<"序列X:"<<endl;  
  29.     output(x,M);  
  30.     cout<<"序列Y:"<<endl;  
  31.     output(y,N);  
  32.   
  33.     LCSLength(M,N,x,y,c,b);  
  34.   
  35.     cout<<"序列X、Y最长公共子序列长度为:"<<c[M][N]<<endl;  
  36.     cout<<"序列X、Y最长公共子序列为:"<<endl;  
  37.     LCS(M,N,x,b);  
  38.     cout<<endl;  
  39. }  
  40.   
  41. void output(char *s,int n)  
  42. {  
  43.     for(int i=1; i<=n; i++)  
  44.     {  
  45.         cout<<s[i]<<" ";  
  46.     }  
  47.     cout<<endl;  
  48. }  
  49.   
  50. void LCSLength(int m,int n,char *x,char *y,int **c,int **b)  
  51. {  
  52.     int i,j;  
  53.   
  54.     for(i=1; i<=m; i++)  
  55.         c[i][0] = 0;  
  56.     for(i=1; i<=n; i++)  
  57.         c[0][i] = 0;  
  58.   
  59.     for(i=1; i<=m; i++)  
  60.     {  
  61.         for(j=1; j<=n; j++)  
  62.         {  
  63.             if(x[i]==y[j])  
  64.             {  
  65.                 c[i][j]=c[i-1][j-1]+1;  
  66.                 b[i][j]=1;  
  67.             }  
  68.             else if(c[i-1][j]>=c[i][j-1])  
  69.             {  
  70.                 c[i][j]=c[i-1][j];  
  71.                 b[i][j]=2;  
  72.             }  
  73.             else  
  74.             {  
  75.                  c[i][j]=c[i][j-1];  
  76.                  b[i][j]=3;  
  77.             }  
  78.         }  
  79.     }  
  80. }  
  81.   
  82. void LCS(int i,int j,char *x,int **b)  
  83. {  
  84.     if(i==0 || j==0)  
  85.     {  
  86.         return;  
  87.     }  
  88.     if(b[i][j]==1)  
  89.     {  
  90.         LCS(i-1,j-1,x,b);  
  91.         cout<<x[i]<<" ";  
  92.     }  
  93.     else if(b[i][j]==2)  
  94.     {  
  95.         LCS(i-1,j,x,b);  
  96.     }  
  97.     else  
  98.     {  
  99.         LCS(i,j-1,x,b);  
  100.     }  
  101. }  

            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 plain  copy
  1. //3d3-2 最长公共子序列问题  
  2. #include "stdafx.h"  
  3. #include <iostream>   
  4. using namespace std;   
  5.   
  6. const int M = 7;  
  7. const int N = 6;  
  8.   
  9. void output(char *s,int n);  
  10. void LCSLength(int m,int n,char *x,char *y,int **c);  
  11. void LCS(int i,int j,char *x,int **c);  
  12.   
  13. int main()  
  14. {  
  15.     //X={A,B,C,B,D,A,B}  
  16.     //Y={B,D,C,A,B,A}  
  17.     char x[] = {' ','A','B','C','B','D','A','B'};  
  18.     char y[] = {' ','B','D','C','A','B','A'};  
  19.   
  20.     int **c = new int *[M+1];  
  21.     for(int i=0;i<=M;i++)    
  22.     {    
  23.         c[i] = new int[N+1];  
  24.     }   
  25.       
  26.     cout<<"序列X:"<<endl;  
  27.     output(x,M);  
  28.     cout<<"序列Y:"<<endl;  
  29.     output(y,N);  
  30.   
  31.     LCSLength(M,N,x,y,c);  
  32.   
  33.     cout<<"序列X、Y最长公共子序列长度为:"<<c[M][N]<<endl;  
  34.     cout<<"序列X、Y最长公共子序列为:"<<endl;  
  35.     LCS(M,N,x,c);  
  36.     cout<<endl;  
  37. }  
  38.   
  39. void output(char *s,int n)  
  40. {  
  41.     for(int i=1; i<=n; i++)  
  42.     {  
  43.         cout<<s[i]<<" ";  
  44.     }  
  45.     cout<<endl;  
  46. }  
  47.   
  48. void LCSLength(int m,int n,char *x,char *y,int **c)  
  49. {  
  50.     int i,j;  
  51.   
  52.     for(i=1; i<=m; i++)  
  53.         c[i][0] = 0;  
  54.     for(i=1; i<=n; i++)  
  55.         c[0][i] = 0;  
  56.   
  57.     for(i=1; i<=m; i++)  
  58.     {  
  59.         for(j=1; j<=n; j++)  
  60.         {  
  61.             if(x[i]==y[j])  
  62.             {  
  63.                 c[i][j]=c[i-1][j-1]+1;  
  64.             }  
  65.             else if(c[i-1][j]>=c[i][j-1])  
  66.             {  
  67.                 c[i][j]=c[i-1][j];  
  68.             }  
  69.             else  
  70.             {  
  71.                  c[i][j]=c[i][j-1];  
  72.             }  
  73.         }  
  74.     }  
  75. }  
  76.   
  77. void LCS(int i,int j,char *x,int **c)  
  78. {  
  79.     if(i==0 || j==0)  
  80.     {  
  81.         return;  
  82.     }  
  83.     if(c[i][j]==c[i-1][j-1]+1)  
  84.     {  
  85.         LCS(i-1,j-1,x,c);  
  86.         cout<<x[i]<<" ";  
  87.     }  
  88.     else if(c[i-1][j]>=c[i][j-1])  
  89.     {  
  90.         LCS(i-1,j,x,c);  
  91.     }  
  92.     else  
  93.     {  
  94.         LCS(i,j-1,x,c);  
  95.     }  
  96. }  

         运行结果如下:

       

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

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

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

[cpp]  view plain  copy
  1. /**  
  2.   头文件------head file  
  3.  */    
  4.   
  5. template <class T>  
  6. class StackNode{  
  7.     public:  
  8.         T data;  
  9.         StackNode *next;  
  10. };  
  11.   
  12. template <class T>  
  13. class Stack{  
  14.     public:  
  15.         Stack(void):top(NULL){}  
  16.         bool IsEmpty(voidconstreturn top==NULL;}  
  17.         void Push(const T data);  
  18.         bool Pop(T *data);  
  19.         bool Peek(T *data) const;  
  20.         StackNode<T> * GetStackNode();  
  21.     private:  
  22.         StackNode<T> *top;  
  23. };  
  24.   
  25. template <class T>  
  26. StackNode<T> * Stack<T>::GetStackNode(){  
  27.     return top;  
  28. }  
  29.   
  30. template <class T>  
  31. void Stack<T>::Push(const T data){  
  32.     StackNode<T> *node = new StackNode<T>();  
  33.     node->data = data;  
  34.     node->next = top;  
  35.     top = node;  
  36. }  
  37.   
  38. template <class T>  
  39. bool Stack<T>::Peek(T *data) const{  
  40.     if(IsEmpty()) return false;  
  41.     *data = top->data;  
  42.     return true;  
  43. }  
  44.   
  45. template <class T>  
  46. bool Stack<T>::Pop(T *data){  
  47.     if(IsEmpty()) return false;  
  48.     *data = top->data;  
  49.     StackNode<T> *node = top;  
  50.     top = top->next;  
  51.     delete(node);  
  52.     return true;  
  53. }  

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

[cpp]  view plain  copy
  1. //3d3-3 所有最长公共子序列问题LCS 矩阵搜索  
  2. #include "stdafx.h"  
  3. #include "stack.h"  
  4. #include <iostream>  
  5. using namespace std;  
  6.   
  7. typedef int **Matrix;  
  8. const int M = 7;  
  9. const int N = 6;  
  10.   
  11. typedef struct _Element  
  12. {  
  13.     int lcslen;//当前节点的LCS长度  
  14.     int row;//当前节点的行坐标  
  15.     int col;//当前节点的列坐标  
  16. }Element;  
  17.   
  18. void output(char *s,int n);  
  19.   
  20. Element CreateElement(int nlen, int row, int col);  
  21.   
  22. Matrix GreateMatrix(int row, int col);  
  23. void DeleteMatrix(Matrix p, int row);  
  24.   
  25. void PrintStack(Stack<Element> *ps, char *str, int len);  
  26. void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype);  
  27.   
  28. void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb);  
  29. void LCS(char *x, Matrix pc, Matrix pb, int row, int col);//矩阵搜索回溯  
  30.   
  31.   
  32. int main(){  
  33.     char x[] = {' ','A','B','C','B','D','A','B'};  
  34.     char y[] = {' ','B','D','C','A','B','A'};  
  35.   
  36.     Matrix b = GreateMatrix(M, N);  
  37.     Matrix c = GreateMatrix(M, N);  
  38.   
  39.     LCSLength(M,N,x,y,c,b);  
  40.   
  41.     cout<<"序列X:"<<endl;  
  42.     output(x,M);  
  43.     cout<<"序列Y:"<<endl;  
  44.     output(y,N);  
  45.   
  46.     cout<<"序列X、Y最长公共子序列长度为:"<<c[M][N]<<endl;  
  47.     cout<<"序列X、Y最长公共子序列为:"<<endl;  
  48.   
  49.     LCS(x,c,b,M,N);  
  50.   
  51.     DeleteMatrix(b,M);  
  52.     DeleteMatrix(c,M);  
  53.   
  54.     return 0;  
  55. }  
  56.   
  57. void output(char *s,int n)  
  58. {  
  59.     for(int i=1; i<=n; i++)  
  60.     {  
  61.         cout<<s[i]<<" ";  
  62.     }  
  63.     cout<<endl;  
  64. }  
  65.   
  66. Element CreateElement(int nlen, int row, int col)  
  67. {  
  68.     Element ele;  
  69.     ele.lcslen = nlen;  
  70.     ele.col = col;  
  71.     ele.row = row;  
  72.     return ele;  
  73. }  
  74.   
  75. Matrix GreateMatrix(int row, int col)  
  76. {  
  77.     Matrix p = new int *[row+1];  
  78.     for(int i=0;i<=row;i++)    
  79.     {    
  80.         p[i] = new int[col+1];  
  81.     }   
  82.     return p;  
  83. }  
  84.   
  85. void DeleteMatrix(Matrix p, int row)  
  86. {  
  87.     for(int i=0;i<=row;i++)    
  88.     {    
  89.         delete []p[i];  
  90.     }  
  91.   
  92.     delete []p;  
  93. }  
  94.   
  95. void PrintStack(Stack<Element> *s,char *str,int len)  
  96. {  
  97.     if(s == NULL || str == NULL)  
  98.         return;  
  99.       
  100.     StackNode<Element> *sn = s->GetStackNode();  
  101.   
  102.     while(sn!=NULL && sn->data.row<=len)  
  103.     {  
  104.         cout<<str[sn->data.row]<<" ";  
  105.         sn = sn->next;  
  106.     }  
  107.   
  108.     cout<<endl;  
  109. }  
  110.   
  111. void SearchE(Matrix pb, int curposx, int curposy, int &eposx, int &eposy, int ntype)  
  112. {  
  113.     switch(pb[curposx][curposy])  
  114.     {  
  115.     case 1:  
  116.         eposx = curposx;  
  117.         eposy = curposy;  
  118.         return;  
  119.     case 2:  
  120.         SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);  
  121.         break;  
  122.     case 3:  
  123.         SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);  
  124.         break;  
  125.     case 4:  
  126.         if(ntype == 0)  
  127.             //搜索e1点,如过碰到分叉点,向上继续搜索  
  128.             SearchE(pb, curposx-1, curposy, eposx, eposy, ntype);  
  129.         else  
  130.             //搜索e2点,如过碰到分叉点,向左继续搜索  
  131.             SearchE(pb, curposx, curposy-1, eposx, eposy, ntype);  
  132.         break;  
  133.     }  
  134. }  
  135.   
  136. void LCSLength(int m,int n,char *x,char *y,Matrix pc,Matrix pb)  
  137. {  
  138.     int i,j;  
  139.   
  140.     for(i=1; i<=m; i++)  
  141.         pc[i][0] = 0;  
  142.     for(i=1; i<=n; i++)  
  143.         pc[0][i] = 0;  
  144.   
  145.     for(i=1; i<=m; i++)  
  146.     {  
  147.         for(j=1; j<=n; j++)  
  148.         {  
  149.             if(x[i]==y[j])  
  150.             {  
  151.                 pc[i][j]=pc[i-1][j-1]+1;  
  152.                 pb[i][j]=1;  
  153.             }  
  154.             else if(pc[i-1][j]>pc[i][j-1])  
  155.             {  
  156.                 pc[i][j]=pc[i-1][j];  
  157.                 pb[i][j]=2;  
  158.             }  
  159.             else if(pc[i-1][j]<pc[i][j-1])  
  160.             {  
  161.                  pc[i][j]=pc[i][j-1];  
  162.                  pb[i][j]=3;  
  163.             }  
  164.             else  
  165.             {  
  166.                 pc[i][j] = pc[i][j-1];//由左节点或上节点转移而来  
  167.                 pb[i][j] = 4;//标记为4  
  168.             }  
  169.         }  
  170.     }  
  171. }  
  172.   
  173. void LCS(char *x, Matrix pc, Matrix pb, int row, int col)  
  174. {  
  175.     if(x == NULL || pc == NULL || pb == NULL)  
  176.         return;  
  177.       
  178.     Stack<Element> store, print;//构造两个栈store,print  
  179.     Element storetop;//store栈的栈顶节点  
  180.     Element element;//临时变量  
  181.     Element virtualnode;//虚拟节点  
  182.     int ntoplen;//保存store栈顶节点的LCS长度  
  183.     int ex1,ey1,ex2,ey2;//矩形搜索的两个节点的坐标  
  184.     int i,j;  
  185.   
  186.     virtualnode = CreateElement(pc[row][col]+1, row+1, col+1);  
  187.   
  188.     store.Push(virtualnode);//压入虚拟节点到store  
  189.   
  190.     while(!store.IsEmpty())  
  191.     {  
  192.         store.Pop(&storetop);  
  193.         if(storetop.row == 1 || storetop.col == 1)//如果是边界节点  
  194.         {  
  195.             print.Push(storetop);  
  196.             PrintStack(&print, x, row);//打印print栈里面除虚拟节点之外的所有节点  
  197.             store.Peek(&element);  
  198.             ntoplen = element.lcslen;//当前store的栈顶节点的LCS长度  
  199.   
  200.             /**********弹出print栈中所有LCS长度小于等于ntoplen的节点**************/  
  201.             while(print.Peek(&element) && element.lcslen<=ntoplen)  
  202.             {  
  203.                 print.Pop(&element);  
  204.             }  
  205.         }  
  206.         else  
  207.         {  
  208.             print.Push(storetop);  
  209.             SearchE(pb, storetop.row-1, storetop.col-1, ex1, ey1, 0);  
  210.             SearchE(pb, storetop.row-1, storetop.col-1, ex2, ey2, 1);/*also other value is ok*/  
  211.   
  212.             if(ex1 == ex2 && ey1 ==ey2)  
  213.             {  
  214.                 element = CreateElement(pc[ex1][ey1], ex1, ey1);  
  215.                 store.Push(element);//压入store栈,回到步骤2  
  216.             }  
  217.             else  
  218.             {  
  219.                 for(i=ex1; i<=ex2; i++)  
  220.                     for(j=ey2; j<=ey1; j++)  
  221.                     {  
  222.                         if(pb[i][j] == 1)  
  223.                         {  
  224.                             element = CreateElement(pc[i][j], i, j);  
  225.                             store.Push(element);  
  226.                         }  
  227.                     }  
  228.             }  
  229.         }  
  230.   
  231.     }  
  232. }  

          矩形搜索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栈,输出其中一个最长公共序列。

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值