字典序最小 - 题目 - Daimayuan Online Judge
题意:
思路:
因为是字典序最小,所以要尽可能是[1,2,3,....N]
考虑用单调栈维护这个子序列
枚举ai,当栈里的元素大于ai时且该位置后面还有这个数时弹出
为什么是这样,如果后面没有这个数,说明就不满足每个数出现一次的条件了
所以我们需要维护每个数出现的最后一个位置
Code:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mxn=1e6+10;
const int mxe=1e6+10;
int M,N;
int a[mxn],last[mxn],is[mxn];
void solve(){
cin>>M>>N;
for(int i=1;i<=M;i++){
cin>>a[i];
last[a[i]]=i;
}
stack<int> S;
for(int i=1;i<=M;i++){
if(is[a[i]]) continue;
while(!S.empty()&&S.top()>a[i]&&last[S.top()]>i){
is[S.top()]=0;
S.pop();
}
S.push(a[i]);
is[a[i]]=1;
}
vector<int> V;
while(!S.empty()){
V.push_back(S.top());
S.pop();
}
reverse(V.begin(),V.end());
for(int i=0;i<V.size();i++) cout<<V[i]<<" \n"[i==V.size()-1];
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int __=1;//cin>>__;
while(__--)solve();return 0;
}