c++ 中多维数组空间的开辟问题??

本文介绍了一种求解两个序列最长公共子序列的算法实现,包括动态规划过程及回溯路径来找出具体最长子序列。文章通过定义数据结构、设置算法步骤详细解释了算法原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 //本程序实现对两个序列求最大公共子序列
#include <iostream>
using namespace std;

#define MAXSIZE 100
#define TRUE    1
#define FALSE   0
typedef char KeyType; // 定义关键字类型为整数类型

typedef struct   
{
 KeyType  key;   //关键字项
// InfoType   otherinfo;   //其它数据型
}RecordType;   //记录类型

typedef struct
{
 RecordType r[MAXSIZE+1];  //r[0]闲置或用作 “ 哨兵单元”
 int length;            //顺序表长度
}SqList;                   //顺序表类型


 
int lcsLength(SqList L1,SqList L2,int b[][])
{
 int m=L1.length-1;
 int n=L2.length-1;
 //int c[][]=new int[m+1][n+1];
 int **c;
 int *b=(int *)malloc((n+1)*sizeof(int));
 for(int i=0;i<=m;i++)
 {
  c[i]=b+i*(n+1)*sizeof(int);
 }
 for(int 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(int j=1;j<=n;j++)
  {
   if(L1.r[i].key==L2.r[j].key)
   {
    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;
    }  
  }////
 return c[m][n];
}

void lcs(int m,int n,char x[],int b[][])
//根据b的内容打印出Xi和Yj的最长公共子序列
{
 int i=m;
 int j=n;
 if(i==0||j==0)
  return ;
 if(b[i][j]==1)
 {
  lcs(i-1,j-1,x,b);
  cout<<x[i]<<endl;
 }
 else
  if(b[i][j]==2)
   lcs(i-1,j,x,b);
  else
   lcs(i,j-1,x,b);   
}

int main()
{
 int i,a,count,xc;
 int m,n;  //L1,L2中的记录数为m,n
 SqList L1,L2;

    //输入要排列的记录数列
jihao:   cout<<"请输入顺序表L1中的记录的个数(注意:最后得到的记录序列是非继减的并且最大排列数不能超过 100个!):"<<endl;
 cin>>m;
 if(m>100)
 {
  cout<<"你输入的记录的个数太大!!!"<<endl;
  return FALSE;
 }
 L1.length=m;
 cout<<"请输入顺序表L1中的记录的个数(注意:最后得到的记录序列是非继减的并且最大排列数不能超过 100个!):"<<endl;
 cin>>n;
 if(n>100)
 {
  cout<<"你输入的记录的个数太大!!!"<<endl;
  return FALSE;
 }
 L2.length=n;

    //输入记录值
 cout<<"记录值全为单位字符!"<<endl;
 cout<<"请输入L1中各个记录的数值:    "<<endl;
 for(i=0;i<=(m-1);i++)
 {
  cout<<"请输入第个"<<i<<"记录的数值:";
  cin>>L1.r[i].key;
  cout<<endl;
 }
 cout<<"请输入L2中各个记录的数值:    "<<endl;
 for(i=0;i<=(n-1);i++)
 {
  cout<<"请输入第个"<<i<<"记录的数值:";
  cin>>L2.r[i].key;
  cout<<endl;
 }
 xc=(m>n)?m:n;
 char *x=(char *)malloc(xc*sizeof(char));

  
    //对两个序列L1,L2求最大公共子序列
 cout<<"请选择要执行的操作: 1 求最大公共子序列,2 重新开始,3 退出程序! ): "<<endl;
 cin>>a; 
 if(a==1)
 {  
  //int b[][]=new int[m][n];
  int **b;
 int *j=(int *)malloc(n*sizeof(int));
 for(int i=0;i<=m;i++)
 {
  b[i]=j+i*n*sizeof(int);
 }
  //执行算法并输出结果
  count=lcsLength(L1,L2,b);
  cout<<"要查找的最大公共子序列的长度为:"<<endl;
  cout<<count<<endl;
  lcs(m,n,x,b);
 }
 else
  if(a==2)
   goto   jihao;
 return TRUE;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值