2021年度训练联盟热身训练赛第一场-E Early Orders-(单调栈)

题目链接:点击进入
题目

在这里插入图片描述
在这里插入图片描述

题意

一个长度 n 的数组,问此数组是否有一个长为 k 的子序列同时这个子序列 1 - k 都出现且仅出现一次,同时要求这个子序列字典序最小,输出此子序列

思路

记录每个数最后出现的位置,从 1 - n 枚举数组,如果 a [ i ] 在栈里出现过跳过看 a [ i + 1 ] ,如果没有出现过,将 a [ i ] 与栈顶元素相比较,如果栈顶元素比 a [ i ] 大,同时 a [ i ] 位置后边还有栈顶元素,那么删去栈顶元素接着比较,直到在栈中找不到满足条件的栈顶或者栈空,此时将 a [ i ] 入栈,枚举下一个数。最后枚举结束,将栈中答案倒序输出即为答案。

代码
#include<iostream>
#include<string>
#include<map>
#include<set>
#include<stack>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131 
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int N=2e4+10;
const int mod=1e9+7;
const double eps=1e-12;
const int maxn=1e6+10;
int n,k,x[maxn],last[maxn],ans[maxn],cnt;
bool vis[maxn];
stack<int>st;
int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);cout.tie(0);
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
        scanf("%d",&x[i]);
    for(int i=1;i<=n;i++)
        if(last[x[i]]<i)
            last[x[i]]=i;
    for(int i=1;i<=n;i++)
    {
        if(vis[x[i]]) continue;
        while(st.size()&&last[st.top()]>i&&x[i]<=st.top())
        {                                                     
            vis[st.top()]=0;
            st.pop();
        }
        if(!vis[x[i]])
        {
            vis[x[i]]=1;
            st.push(x[i]);
        }
    }
    while(st.size())
    {
        ans[cnt++]=st.top();
        st.pop();
    }
    for(int i=cnt-1;i>=0;i--)
        printf("%d ",ans[i]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值