题目链接:点击这里
题目大意:
给定
n
,
k
n,k
n,k 和一个长度为
n
n
n 的序列
a
i
(
a
i
≤
k
)
a_i(a_i\le k)
ai(ai≤k) ,求一个
a
i
a_i
ai 的子序列,其包含
1
1
1 到
k
k
k 的所有数字各一个,求这些子序列中字典序最小的子序列
题目分析:
因为要求字典序最小的子序列,其具有一定的单调性,考虑使用单调栈维护序列
当我们要插入
a
i
a_i
ai 时,如果栈顶元素大小大于
a
i
a_i
ai 且 存在
a
j
(
i
≤
j
)
a_j(i\le j)
aj(i≤j) 等于栈顶元素,就可以将栈顶元素弹出来减小栈中元素的字典序(因为后继还会出现栈顶元素所有不必担心弹出元素会导致最终序列缺少某个元素)
最终答案就是栈中的元素序列
具体细节见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 2e5+5;
const int maxm = 3e4+5;
const int mod = 998244353;
const double pi = acos(-1);
const double eps = 1e-8;
int n,k,top,a[maxn],last[maxn],st[maxn];
bool vis[maxn];
signed main()
{
n = read(),k = read();
for(int i = 1;i <= n;i++) a[i] = read(),last[a[i]] = i;
for(int i = 1;i <= n;i++)
{
if(vis[a[i]]) continue;
while(st[top] > a[i] && last[st[top]] > i) vis[st[top--]] = false;
st[++top] = a[i];
vis[a[i]] = true;
}
for(int i = 1;i <= k;i++) printf("%d%c",st[i],i==n ? '\n' : ' ');
return 0;
}