Early Orders(单调栈)

题目链接:点击这里

题目大意:
给定 n , k n,k n,k 和一个长度为 n n n 的序列 a i ( a i ≤ k ) a_i(a_i\le k) ai(aik) ,求一个 a i a_i ai 的子序列,其包含 1 1 1 k k k 的所有数字各一个,求这些子序列中字典序最小的子序列

题目分析:
因为要求字典序最小的子序列,其具有一定的单调性,考虑使用单调栈维护序列
当我们要插入 a i a_i ai 时,如果栈顶元素大小大于 a i a_i ai 且 存在 a j ( i ≤ j ) a_j(i\le j) aj(ij) 等于栈顶元素,就可以将栈顶元素弹出来减小栈中元素的字典序(因为后继还会出现栈顶元素所有不必担心弹出元素会导致最终序列缺少某个元素)
最终答案就是栈中的元素序列

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 2e5+5;
const int maxm = 3e4+5;
const int mod = 998244353;
const double pi = acos(-1);
const double eps = 1e-8;
int n,k,top,a[maxn],last[maxn],st[maxn];
bool vis[maxn]; 
signed main()
{
	n = read(),k = read();
	for(int i = 1;i <= n;i++) a[i] = read(),last[a[i]] = i;
	for(int i = 1;i <= n;i++)
	{
		if(vis[a[i]]) continue;
		while(st[top] > a[i] && last[st[top]] > i) vis[st[top--]] = false;
		st[++top] = a[i];
		vis[a[i]] = true;
	}
	for(int i = 1;i <= k;i++) printf("%d%c",st[i],i==n ? '\n' : ' ');
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值