Early Orders
思路
贪心+单调栈
主要思想:可以看出,当栈顶元素要大于待入队元素时,看是否该栈顶元素后面是否还存在该数,有则将栈顶元素弹出。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
const int N = 200010;
stack<int> S;
int cnt[N];
int a[N];
int n, m;
bool st[N];
int ans[N];
int main() {
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++) {
scanf("%d", &a[i]);
cnt[a[i]] ++;
}
S.push(a[0]);
st[a[0]] = true;
cnt[a[0]] --;
for(int i = 1; i < n; i ++) {
cnt[a[i]] --;
while(S.size() && (a[i] < S.top()) && !st[a[i]] && (cnt[S.top()] > 0)) {
st[S.top()] = false;
S.pop();
}
if(!st[a[i]]) {
S.push(a[i]);
st[a[i]] = true;
}
}
int num = 0;
while(!S.empty()) {
int t = S.top();
ans[num ++] = t;
S.pop();
}
for(int i = num - 1; i >= 0; i --)
printf("%d ", ans[i]);
return 0;
}