最长公共子序列

来源:互联网 发布:程序员排名 编辑:程序博客网 时间:2024/04/29 16:21

        最长公共子序列,英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。而最长公共子串(要求连续)和最长公共子序列是不同的。

动态规划的一个计算两个序列的最长公共子序列的方法如下:
以两个序列 X、Y 为例子:
设有二维数组f[i,j] 表示 X 的 i 位和 Y 的 j 位之前的最长公共子序列的长度,则有:
f[1][1] = same(1,1);
f[i,j] = max{f[i-1][j -1] + same(i,j),f[i-1,j],f[i,j-1]}
其中,same(a,b)当 X 的第 a 位与 Y 的第 b 位相同时为“1”,否则为“0”。
此时,二维数组中最大的数便是 X 和 Y 的最长公共子序列的长度,依据该数组回溯,便可找出最长公共子序列。
该算法的空间、时间复杂度均为O(n^2),经过优化后,空间复杂度可为O(n)。
代码如下:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;#define N 1005int n, a[N][N], len1, len2;char str1[N], str2[N], res[N];void display(int x, int y, int th, int max_len)//打印所有的最长公共子序列{      if (x==0 || y==0)      {            for (int i=0; i<max_len; i++)                  cout << res[i];            cout << endl;            return ;      }      if (str1[x-1]==str2[y-1])      {            th--;            res[th] = str1[x-1];            display(x-1, y-1, th, max_len);      }      else      {            if (a[x][y]==a[x-1][y])            {                  display(x-1, y, th, max_len);            }            if (a[x][y]==a[x][y-1])            {                  display(x, y-1, th, max_len);            }      }}int main(){      cin >> n;      while (n--)      {            cin>>str1>>str2;            len1 = strlen(str1);            len2 = strlen(str2);            for (int i=0; i<=len1; i++)                  a[i][0] = 0;            for (int i=0; i<=len2; i++)                  a[0][i] = 0;            for (int i=1; i<=len1; i++)                  for (int j=1; j<=len2; j++)                        if (str1[i-1]==str2[j-1])                              a[i][j] = a[i-1][j-1] + 1;                        else                              a[i][j] = max(a[i-1][j], a[i][j-1]);//            for (int i=0; i<=len1; i++)//            {//                  for (int j=0; j<=len2; j++)//                        cout << a[i][j] << " ";//                  cout << endl;//            }//            display(len1, len2, a[len1][len2], a[len1][len2]);            cout << a[len1][len2] << endl;      }      return 0;}