PAT甲级真题-1045 Favorite Color Stripe详解优化

1045 Favorite Color Stripe

题目链接

https://pintia.cn/problem-sets/994805342720868352/problems/994805437411475456

解题思路

题目意思是,给定颜色的出现顺序,再给一个长序列,求出符合顺序的最长序列。
1.最长递增子序列解法

1.用lev[i]记录第i种颜色的下标,即颜色的出现顺序;
2.遍历第二个序列,剔除未曾出现的颜色;
3.根据颜色的出现顺序求出其最长递增子序列;

代码展示
1.最长递增子序列

#include<bits/stdc++.h>
using namespace std;
/*
思路:
字符出现的顺序要一致
6
5 1 2 3 4 5
5 1 2 5 3 4
*/
int lev[205],L[10005];
int num[10005];
int main(){
	int n,m,l;
	cin>>n; 
	cin>>m;
	for(int i=0;i<m;i++){
		int x;
		cin>>x;
		lev[x]=i+1;
	}
	cin>>l;int k=0;
	for(int i=0;i<l;i++){
		int x;
		cin>>x;
		if(lev[x]>=1)L[k++]=x;
	}
	int ans=0;
	for(int i=0;i<k;i++){
		num[i]=1;
		for(int j=0;j<i;j++){
			if(lev[L[i]]>=lev[L[j]]&&num[i]<num[j]+1)
				num[i]=num[j]+1;
			ans=max(ans,num[i]);
		}
	}
	cout<<ans<<endl;
   return 0;
   
}

2.最长公共子序列解法

1.我原本的思路就是用公共序列,但不知道如何处理颜色重复出现的情况;随后看了别人的解法。

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
/*
思路:
LCS
6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6
*/
int lev[205],L[10005];
int dp[10005][10005];
int main(){
	int n,m,l;
	cin>>n; 
	cin>>m;
	for(int i=1;i<=m;i++){
		int x;
		cin>>x;
		lev[i]=x;
	}
	cin>>l;
	for(int i=1;i<=l;i++){
		cin>>L[i];
	}
	for(int i=1;i<=m;i++){
		for(int j=1;j<=l;j++){
			int maxx=max(dp[i-1][j],dp[i][j-1]);
			maxx=max(maxx,dp[i-1][j-1]);
			if(lev[i]==L[j])
				dp[i][j]=maxx+1;
			else dp[i][j]=maxx; 
		}
	}
	cout<<dp[m][l]<<endl;
   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、付费专栏及课程。

余额充值