萌新求最长上升子序列错了/kk,求助!
  • 板块学术版
  • 楼主Belarus
  • 当前回复5
  • 已保存回复5
  • 发布时间2020/10/31 07:54
  • 上次更新2023/11/5 09:27:19
查看原帖
萌新求最长上升子序列错了/kk,求助!
223392
Belarus楼主2020/10/31 07:54

rt:
思路是这样的:
开一个栈,每次取栈顶元素top和读到的元素x做比较,如果x > top 则将x入栈;如果x < top则二分查找栈中的比x大的第1个数,并用x替换它。 最长序列长度即为栈的大小top。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=10010;
int n,stk[N],top=0;
int main(){
	ios::sync_with_stdio(0);
	cin>>n;
	for(int i=1;i<=n;++i){
		int x;
		cin>>x;
		if(x>stk[top]){stk[++top]=x;continue;}
		int pos=lower_bound(stk+1,stk+top+1,x)-stk;
		stk[pos]=x;
	}
	cout<<top<<'\n';
	return 0;
}
2020/10/31 07:54
加载中...