Week10 B - LIS & LCS

Week10 B - LIS & LCS
东东有两个序列A和B。

他想要知道序列A的LIS和序列AB的LCS的长度。

注意,LIS为严格递增的,即a1<a2<…<ak(ai<=1,000,000,000)。

Input
第一行两个数n,m(1<=n<=5,000,1<=m<=5,000)
第二行n个数,表示序列A
第三行m个数,表示序列B

Output
输出一行数据ans1和ans2,分别代表序列A的LIS和序列AB的LCS的长度

Simple Input

5 5
1 3 2 5 4
2 4 3 1 5
  • 1
  • 2
  • 3

Simple Output

3 2
  • 1

解题思路
dp动态规划
LIS
fi=max ( fi | j < i ^ Aj < Ai )+1
LCS
初始化 f[0][1]=f[1][0]=f[0][0]=0
当 Ai=Bj 时 f[i][j]=f[i-1][j-1]+1
否则 f[i][j]=max(f[i-1][j] , f[i][j-1])

Code

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int m,n;
int a[2][5010];
int aa[50100];
int b[2][5010];
int dp[5010];
int f[5010][5010];
int main(){
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[0][i]);
	}
	for(int i=1;i<=m;i++){
		scanf("%d",&b[0][i]);
	}
	int ans=-1;
	int anss;
	for(int i=1;i<=n;i++){
		dp[i]=1;
		for(int y=1;y<i;y++){
			if(a[0][y]<a[0][i]){
				dp[i]=max(dp[i],dp[y]+1);
				/*if(dp[i]<dp[y]+1){
					dp[i]=dp[y]+1;
					a[1][i]=y;
				}*/
			}
		}
		/*if(dp[i]>ans){
			anss=i;
		}*/
		ans=max(dp[i],ans);
	}
	printf("%d ",ans);
	/*aa[0]=a[0][anss]<<' ';
	for(int i=0;i<ans-1;i++){
		aa[i+1]=a[0][a[1][anss]];
		anss=a[1][anss];
	}
	for(int i=ans-1;i>=0;i--){
		cout<<aa[i];
		//if(i!=0){
			cout<<' ';
		//}
	}//cout<<endl;*/
	ans=0;
	f[0][1]=f[1][0]=f[0][0]=0;
	for(int i=1;i<=n;i++){
		for(int y=1;y<=m;y++){
			if(a[0][i]==b[0][y]){
				f[i][y]=f[i-1][y-1]+1;
				//b[1][i]=i-1;
			}else{
				/*if(f[i-1][y]>f[i][y-1]){
					b[1][i]=i-1;
				}else{
					b[1][i]=i;
				}*/
				f[i][y]=max(f[i-1][y],f[i][y-1]);
			}
			ans=max(ans,f[i][y]);
		}
	}
	printf("%d",f[n][m]);
	//cout<<ans<<endl;
	/*for(int i=0;i<ans;i++){
		cout<<b[0][ans]<<' ';
		ans--;
	}*/
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他
点击体验
DeepSeekR1满血版
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回顶部

登录后您可以享受以下权益:

×