Perfect Flush 单调栈
题目链接:https://nanti.jisuanke.com/t/45345
题意:给你\(n\)个值域为\([1,k]\)的数,求该数组长度为\(k\)最小字典序子序列,并且该子序列所有数只出现一次(\(k\)的一种排列)
维护一个单调递增栈(栈底到栈顶递增),并保证栈内元素不重不漏,倒序输出栈内元素即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=200010;
int a[maxn];
int ans[maxn],cnt[maxn],vis[maxn];
stack<int>st;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int k,n;
cin>>n>>k;
for(int i=0;i<n;i++)
{
cin>>a[i];
cnt[a[i]]++;
}
for(int i=0;i<n;i++)
{
cnt[a[i]]--;
if(vis[a[i]])continue;
while(!st.empty()&&a[i]<st.top()&&cnt[st.top()]>0)
{
vis[st.top()]=0;
st.pop();
}
st.push(a[i]);
vis[a[i]]=1;
}
for(int i=1;i<=k;i++)
{
ans[i]=st.top();
st.pop();
}
for(int i=k;i>=1;i--)
{
cout<<ans[i];
if(i!=1)cout<<' ';
else cout<<endl;
}
return 0;
}

浙公网安备 33010602011771号