思路:
打CF #710Div.3 的G题知道原题回来补的,原本思路感觉和这个差不多,但是万万没想到用单调栈来直线就很简单了。
具体实现还是参考了大佬博客,简直不要太nice!(具体思路见代码注释。)
代码实现:
#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll mod = 1e9+7;
const int N = 2e5 + 5;
inline void read(int &x){
char t=getchar();
while(!isdigit(t)) t=getchar();
for(x=t^48,t=getchar();isdigit(t);t=getchar()) x=x*10+(t^48);
}
int n, k, a[N], lst[N], ans[N];
map<int, int> vis;
signed main()
{
IOS;
cin >> n >> k;
for(int i = 1; i <= n; i ++){
cin >> a[i];
lst[a[i]] = i; //记录该数字出现的最后位置
}
for(int i = 1, j = 0; i <= n; i ++){
if(vis[a[i]]) continue; //如果这个数字已经被确定了位置
while(ans[j]>a[i]&&lst[ans[j]]>i) //如果栈顶的数字比即将入栈的数字大,且它后面还可以再有机会入栈
vis[ans[j--]] = 0;
ans[++j] = a[i]; //确定当前数组的位置
vis[a[i]] = 1; //并且标记该数字已经确定位置
}
for(int i = 1; i <= k; i ++)
cout << ans[i] << " \n"[i==k];
return 0;
}