这个题,如果想在暴力的基础上进行优化,发现没有好的办法,但是如果想到用栈来存储结果,那么,一切就变得理所当然了,但是,做题的事实却总是陷在优化暴力上出不来,不愿意去或者是害怕换一种思想。
#include <bits/stdc++.h>
#define int long long
#define ioss ios::sync_with_stdio(0), cin.tie(0)
using namespace std;
template <class cl>
void read(cl &x)
{
x = 0;
int f = 0;
char ch;
ch = getchar();
while (!isdigit(ch))
{
f = f | (ch == '-'), ch = getchar();
}
while (isdigit(ch))
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
x = f ? -x : x;
return;
}
template <class cl>
void put(cl x)
{
if (x < 0)
putchar('-'), x = -x;
if (x > 9)
put(x / 10);
putchar(x % 10 + '0');
return;
}
const int N=2e5+10;
int a[N];
int xx[N];
int st[N];
int vis[N];
int cnt;
inline void to()
{
int n,k;
read(n);
read(k);
// int tt=k;
for(int i=1;i<=n;i++)
{
read(a[i]);
xx[a[i]]++;
}
for(int i=1;i<=n;i++)
{
if(vis[a[i]])
{
xx[a[i]]--;
continue;
}
while(cnt!=0&&a[i]<st[cnt]&&xx[st[cnt]]>1) //这里要确保后续一定还有这个值。
{
vis[st[cnt]]--;// 这里确定这个值不被用。
xx[st[cnt]]--;//这里这个值不被用 要变回来。
cnt--;
}
st[++cnt]=a[i];
vis[a[i]]=1; // 这里入栈时并不能写上 xx[a[i]]-- ,因为这里没有确定该值没被用
}
for(int i=1;i<=cnt-1;i++)
{
put(st[i]);
putchar(' ');
}
put(st[cnt]);
puts("");
return ;
}
signed main()
{
to();
return 0;
}