dp训练 51nod 1006

先跑一遍lcs得到最长公共子序列长度,再倒着跑一遍记录路径,即dp[i][j]刚开始发生改变的地方

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1010;
char s1[maxn],s2[maxn],path[maxn];
int dp[maxn][maxn];
int len1,len2;
void lcs(char s1[], char s2[])
{ //cout<<strlen(s1)<<endl<<strlen(s2)<<endl;
	int len1 = strlen(s1),len2 = strlen(s2);
	for(int i = 0; i<len1; i++){
		for(int j = 0; j<len2; j++){
			if(s1[i]==s2[j]){
				dp[i+1][j+1]=dp[i][j]+1;
			}
			else{
				dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);
			}
		}
	}
}
void work(char s1[],char s2[])
{
	int plen = 0,len1 = strlen(s1),len2 = strlen(s2);
	int i = len1 -1 ;
	int j= len2 -1;
	while(i>=0&&j>=0){
		if(s1[i]==s2[j]){
			path[plen++] = s1[i];
			i--,j--;
		}
		else if(dp[i+1][j]>=dp[i][j+1]){
			j--;
		}
		else {
			i--;
		}
	}
	reverse(path,path+plen);
}
int main()
{
	scanf("%s",s1);
	scanf("%s",s2);
	 len1 = strlen(s1);
	 len2 = strlen(s2);
	if(len1<=len2) lcs(s1,s2),work(s1,s2);
	else lcs(s2,s1),work(s2,s1);//cout<<dp[len1][len2]<<endl;
	puts(path);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值