[ABC299G] Minimum Permutation
思路
首先我们要明白这道题让我们求什么,很明显是一个包含了所有数的字典序最小的子序列,那么字典序最小就意味着越靠前面的越小肯定越好,同时也要记录下这个序列是什么,考虑使用单调栈进行维护。
实现
我们发现我们做这道题的矛盾点在哪,就是在不敢乱出栈,因为可能后面就没有这个数了,怎么办?
很明显,缺啥补啥,开一个
然后我们就开始往后扫,每次扫到一个数,首先按照单调栈,如果他是一个小的数,那么肯定越往前插越好, 同时又需要考虑我们扔掉的数后面会不会再出现,如果说我们比较的是队伍中的第
那么我们在连续弹栈的判断条件很容易得出就是
while(!sta.empty() && sta.top() > a[i] && lst[sta.top()] > i)
vis[sta.top()] = 0, sta.pop();
那么这道题...其实就迎刃而解了。
Code
#include<bits/stdc++.h>
#define N 200010
int o = N;
#define reg register
using namespace std;
//char in[1 << 20] ,*ss = in,*tt = in;
//#define getchar() (tt == ss && (tt = (ss = in) + fread(in, 1, 1 << 20,stdin),ss == tt) ? EOF : *ss++)
inline int read(){
int x = 0, f = 1; char ch = getchar();
while(ch > '9' || ch < '0'){
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = (x << 3) + (x << 1) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
stack<int> sta;
map<int, int> lst, vis;
int n ,m, cnt;
int a[N], ans[N];
signed main(){
n = read(), m = read();
for(reg int i = 1;i <= n;i = -~i) a[i] = read(), lst[a[i]] = i;
for(reg int i = 1;i <= n;i = -~i) {
if(vis[a[i]]) continue;
while(!sta.empty() && sta.top() > a[i] && lst[sta.top()] > i) vis[sta.top()] = 0, sta.pop();
sta.push(a[i]);
vis[a[i]] = 1;
}
while(!sta.empty()) {
int h = sta.top();
ans[++ cnt] = h;
sta.pop();
}
for(reg int i = cnt;i >= 1;-- i) printf("%d ", ans[i]);
return o;