解题思路:单调栈。单调栈中保持单调递增的序列,如果出现某个数大于栈顶的元素,就把该元素加进去,如果出现某个数小于栈顶的元素,判断在序列后面是否还有栈顶元素,如果有的话可以去掉,如果没有的话,该元素直接加进去。
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<ll,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 2e5+10;
const ull base = 131;
const ll mod = 1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){str+=s;s=getchar();}return str;}
int random(int n){return (int)(rand()*rand())%n;}
void writestring(string s){int n = s.size();for(int i = 0;i < n;i++){printf("%c",s[i]);}}
ll fast_power(ll a,ll p){
ll ans = 1;
while(p){
if(p&1) ans = (ans*a)%mod;
p >>= 1;
a = (a*a)%mod;
}
return ans;
}
int a[N];
int sum[N];
int vis[N];
stack<int>st;
int main(){
srand((unsigned)time(NULL));
//freopen( "out.txt","w",stdout);
int n = read(),k = read();
for(int i = 1;i <= n;i++){
a[i] = read();
sum[a[i]]++;
}
for(int i= 1;i <= n;i++){
sum[a[i]]--;
if(vis[a[i]]) continue;
if(st.size()==0||a[i]>st.top()){
st.push(a[i]);
vis[a[i]] = 1;
}else {
while(st.size()&&a[i]<st.top()&&sum[st.top()]){
vis[st.top()] = 0;
st.pop();
}
st.push(a[i]);
vis[a[i]] = 1;
}
}
vector<int>ans;
while(st.size()){
ans.push_back(st.top());
st.pop();
}
reverse(ans.begin(),ans.end());
for(int i = 0;i < ans.size();i++){
printf("%d ",ans[i]);
}
return 0;
}
/*
8 5
1 4 3 2 1 4 5 5
*/