LCS 及路径输出

单纯LCS

#include <bits/stdc++.h> 
using namespace std;
string  s1,s2;
int f[1010][1010],len1,len2,ans;
int main(){
	cin>>s1>>s2;
	len1=s1.size();
	len2=s2.size();

	for(int i=1;i<=len1;i++)
		for(int j=1;j<=len2;j++)
		{
			if(s1[i-1]!=s2[j-1])f[i][j]=max(f[i-1][j],f[i][j-1]);
			else{
			f[i][j]=f[i-1][j-1]+1; 
		}
		
		} 
cout<<f[len1][len2];
	return 0;
	
}

LCS 及路径输出

#include <bits/stdc++.h>
using namespace std;
const int N=1010;
string s1,s2;
int n,f[N][N],b[N][N],len1,len2;
void lcs(){
	for(int i=1;i<=len1;i++)
		for(int j=1;j<=len2;j++){
			if(s1[i-1]==s2[j-1]){
				f[i][j]=f[i-1][j-1]+1;
				b[i][j]=1;//b数组记录路径 
			}
			else {
				if(f[i][j-1]>=f[i-1][j]){
					f[i][j]=f[i][j-1];
					b[i][j]=2;
				}
				else {
					f[i][j]=f[i-1][j];
					b[i][j]=3;
				}
				
			}
		}
}
//递归输出正序路径 
void print(int i,int j){
	if(i==0||j==0)return;
	if(b[i][j]==1){
		print(i-1,j-1);
		cout<<s1[i-1];
	}
	else if(b[i][j]==2){
		print(i,j-1);
		
	}
	else 
		print(i-1,j);
}
int main(){
	cin>>s1>>s2;
	len1=s1.size();
	len2=s2.size();
	lcs();
	cout<<f[len1][len2];
	print(len1,len2);
//	cout<<endl;
//	for(int i=0;i<=len1;i++){
//		for(int j=0;j<=len2;j++)
//			cout<<f[i][j]<<" ";	
//		cout<<endl;
//	}
//	cout<<endl;
//	for(int i=0;i<=len1;i++){
//		for(int j=0;j<=len2;j++)
//			cout<<b[i][j]<<" ";	
//		cout<<endl;
//	}
	return 0;
	
}

参考:
LCS参考博文https://blog.csdn.net/hrn1216/article/details/51534607
路径输出参考《趣学算法》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值