动态规划 最长公共子序列

//头文件

//LCSLength
//X[] 为X序列  Y[] 为Y序列
//c[i][j]存储Xi,Yj的最长公共子序列的长度
//b[i][j]记录c[i][j]的值是由哪一个子问题的截得到的
//c[i][j]= | 0;    (i=0,j=0;)
//c[i][j]= | c[i-1][j-1]; (x[i]=y[j])  b[i][j]=1
//c[i][j]= | max{c[i][j-1],c[i-1][j]};  b[i][j]=2表示c[i][j]=c[i][j-1],  b[i][j]=3表示c[i][j]=c[i-1][j]
template<int m,int n>//m为行数,n位列数
void LCSLength(char* x,char* y,int (&c)[m][n], int (&b)[m][n])
{
 int row=m-1;
 int colum=n-1;
 c[0][0]=0;
 for (int i=1;i<=row;i++)
 {
  c[i][0]=0;
 }
 for (int i=1;i<=colum;i++)
 {
  c[0][i]=0;
 }
 for (int i=1;i<=row;i++)
 {
  for (int j=1;j<=colum;j++)
  {
   if (x[i]==y[j])
   {
    c[i][j]=c[i-1][j-1]+1;
    b[i][j]=1;
   }
   else if (c[i][j-1]>=c[i-1][j])
   {
    c[i][j]=c[i][j-1];
    b[i][j]=2;
   }
   else
   {
    c[i][j]=c[i-1][j];
    b[i][j]=3;
   }
  }
 }

}

//主程序

// LCSLength.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include "LCSLength.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
 const int m=5,n=6;
 char x[m+1]={' ','e','b','c','c','d'};
 char y[n+1]={' ','g','b','c','f','r','c'};
 int c[m+1][n+1]  ={0};
 int b[m+1][n+1]  ={0};
 LCSLength(x,y,c,b);
 std::string strlcs="";
 std::cout<<"最长公共子序列长度"<<c[m][n]<<std::endl;
 int row=m,colum=n;
 do
 {
  if (b[row][colum]==1)
  {
   strlcs=y[colum]+strlcs;
   --row;
   --colum;
  }
  else if (b[row][colum]==2)
  {
   --colum;
  }
  else
  {
   --row;
  }
 } while (row!=0&&colum!=0);
 std::cout<<"公共子序列为"<<strlcs<<std::endl;
 return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值