3-4最长公共子序列(动态规划)

本文详细介绍了如何使用动态规划解决最长公共子序列问题,并提供了三种不同的实现方法及其代码示例,帮助读者深入理解该算法的工作原理。

3-4 最长公共子序列

一、题目

在这里插入图片描述

二、分析

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

三、代码

//最长公共子序列
#include<iostream>
#include<string.h>
#include<algorithm> 
using namespace std;
int c[100][100];//c[i][j]记录最长公共子序列的长度
int s[100][100];//为了构造最优解使用的 
string x,y;
void Print(int a[100][100],int m,int n){
	cout<<"---------------------\n"; 
	for(int i=0;i<=m;i++){
		for(int j=0;j<=n;j++){
			cout<<a[i][j]<<" ";
		}
		cout<<endl; 
	}
	cout<<"-------------------------\n";
}
void LCSLength(int m,int n){
	for(int i=1;i<=m;i++) c[i][0]=0;//初始化 
	for(int j=1;j<=n;j++) c[0][j]=0;//初始化 i==0||j==0表示一个序列为空,故c[i][j]=0; 
	for(int i=1;i<=m;i++){
		for(int j=1;j<=n;j++){
			if(x[i]==y[j]){
				c[i][j]=c[i-1][j-1]+1;
				s[i][j]=1;
			}
			else{
				if(c[i-1][j]>=c[i][j-1]){
					c[i][j]=c[i-1][j];
					s[i][j]=2;
				}
				else{
					c[i][j]=c[i][j-1];
					s[i][j]=3;
				}
			}					
		}
	}
}
void LCS(int i,int j){  //用了辅助数组s[i][j] 
	if(i==0||j==0) return;
	if(s[i][j]==1){
		LCS(i-1,j-1);
		cout<<x[i]; 
	} 
	else if(s[i][j]==2)
		LCS(i-1,j);
	else if(s[i][j]==3)
		LCS(i,j-1);	
}
void LCS2(int i,int j){  //不用辅助数组s[i][j] 
	if(i==0||j==0) return;
	if(x[i]==y[j]){
		LCS(i-1,j-1);
		cout<<x[i]; 
	} 
	else if(c[i-1][j]>=c[i][j-1])
		LCS(i-1,j);
	else if(c[i-1][j]<c[i][j-1])
		LCS(i,j-1);	
}
void LCS3(int i,int j){  //不用辅助数组s[i][j] 
	if(i==0||j==0) return;
	if(c[i][j]==c[i-1][j-1]+1){
		LCS(i-1,j-1);
		cout<<x[i]; 
	} 
	else if(c[i][j]==c[i-1][j])
		LCS(i-1,j);
	else if(c[i][j]==c[i][j-1])
		LCS(i,j-1);
}
int main(){
	int m,n;
//	cin>>x>>y;
	x="abc";
	y="ac";	
	m=x.length();
	n=y.length();	
	cout<<"m="<<m<<" n="<<n<<endl;
	x=' '+x;
	y=' '+y;
	LCSLength(m,n);//求解最优值 
	cout<<"LCS=";
	LCS(m,n); //构造最优解 
	cout<<"\nLCS2=";
	LCS2(m,n);//法2 构造最优解 
	cout<<"\nLCS3=";
	LCS3(m,n);//法2 构造最优解 
	
	cout<<"\ncij\n";
	Print(c,m,n);
	cout<<"sij\n";
	Print(s,m,n);
	
	return 0;
} 

四、运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清木!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值