Nearth==>动态规划算法003/最长公共子序列算法

运行效果:


代码学习:

#include<iostream>
using namespace std;
#define MAX 1000//输入字符串的最大长度
char a[MAX]={0};//输入的字符串1
char b[MAX]={0};//输入的字符串2
int flag[MAX][MAX];//为了输出字符串1,2的共同字符所设下的标志
int count[MAX][MAX]={0};//字符串1,2的最长公共子长度
void print(int i,int j){//根据标志控制输出公共字符的函数
	if(i==0||j==0){
	return ;
	}
	if(flag[i][j]==1){
	  print(i-1,j-1);
	  cout<<a[i-1];
	}
	else if(flag[i][j]==2){
	  print(i-1,j);
	}
	else if(flag[i][j]==3){
	print(i,j-1);
	}
}
void LCSLength(){
    cout<<"请输入子序列1(长度不能超过1000):";
	cin>>a;
	cout<<"请输入子序列2(长度不能超过1000):";
	cin>>b;
	int lengthA=strlen(a);
	int lengthB=strlen(b);
	for(int i=1;i<=lengthA;i++){
		for(int j=1;j<=lengthB;j++){
			if(a[i]==b[j]){//如果最后字符串1,2的最后一个字符相同,则这两个字符串的最大公共字符串长度为->
			count[i][j]=count[i-1][j-1]+1;//->count[i-1][j-1]+1
			flag[i][j]=1;
			}
			else{
				if(count[i-1][j]>count[i][j-1]){
				count[i][j]=count[i-1][j];
				flag[i][j]=2;
				}
				else{
				count[i][j]=count[i][j-1];
				flag[i][j]=3;
				}
			}
		}
	}
	cout<<"*******************************************************"<<endl;
	cout<<"******************测试结果如下*************************"<<endl;
	cout<<"两个子序列的最长公共子序列长度为:"<<count[lengthA][lengthB]<<endl;
	cout<<"最长公共子序列为:";
	print(lengthA,lengthB);
	cout<<endl;
}
int main(){
	int i=1;
	cout<<"*******************************************************"<<endl;
	cout<<"*****************最长公共子序列算法********************"<<endl;
	cout<<"*******************************************************"<<endl;
	while(i<20){
	cout<<"--------------第"<<i++<<"次操作"<<"-----------------------"<<endl;
	cout<<"******************测试指示如下*************************"<<endl;
	LCSLength();
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码字界陈冠希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值