算法导论之动态规划:最长公共子序列

#include <iostream>
#include <errno.h>


using namespace std;


#define X_LEN 7
#define Y_LEN 6
#define EQUAL 0
#define UP 1
#define LEVEL 2


void lcs_length(char *X, char *Y, int c[X_LEN+1][Y_LEN+1], int b[X_LEN+1][Y_LEN+1]);
void print_lcs(int b[X_LEN+1][Y_LEN+1], char *X, int i, int j);


int main()
{
  char X[X_LEN+1] = {' ','A','B','C','B','D','A','B'};
  char Y[Y_LEN+1] = {' ','B','D','C','A','B','A'};
  int c[X_LEN+1][Y_LEN+1];
  int b[X_LEN+1][Y_LEN+1];
  int i,j;
  lcs_length(X, Y, c, b);
  for(i = 0; i <= X_LEN; i++)
    {
      for(j = 0; j <= Y_LEN; j++)
        cout<<c[i][j]<<" ";
      cout<<endl;
    }
  cout<<"The length of LCS is: "<<c[X_LEN][Y_LEN]<<endl;
  cout<<"The longest common subsequence between X and Y is: "<<endl;
  print_lcs(b, X, X_LEN, Y_LEN);
  cout<<endl;
  return 0;
}


void lcs_length(char *X, char *Y, int c[X_LEN+1][Y_LEN+1], int b[X_LEN+1][Y_LEN+1])
{
  int i,j;
  for(i = 0; i <= X_LEN; i++)
    c[i][0] = 0;
  for(j = 0; j <= Y_LEN; j++)
    c[0][j] = 0;
  /* if(x[i] == y[j])
       c[i][j] = c[i-1][j-1]+1;  b [i][j] = EQUAL;
    else if(up > left)
       c[i][j] = up; b[i][j] = UP;
    else c[i][j] = left; b[i][j] = LEFT;
  */
  for(i = 1; i <= X_LEN; i++)
    {
      for(j = 1; j <= Y_LEN; j++)
        {
          if(X[i] == Y[j])
            {
              c[i][j] = c[i][j] + 1;
              b[i][j] = EQUAL;
            }
          else if(c[i-1][j] >= c[i][j-1])
            {
              c[i][j] = c[i-1][j];
              b[i][j] = UP;
            }
          else
            {
              c[i][j] = c[i][j-1];
              b[i][j] = LEVEL;
            }
        }
    }
}


void print_lcs(int b[X_LEN+1][Y_LEN+1],char * X,int i,int j)
{
  if(i == 0 || j == 0)
    return;
  if(b[i][j] == EQUAL)
    {
      print_lcs(b, X, i-1, j-1);
      putchar(X[i]);
    }
  else if(b[i][j] == UP)
    {
      print_lcs(b, X, i-1, j);
    }
  else
    print_lcs(b, X, i, j-1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值