题目链接:E. Early Orders
题解
题目大意是给一个长度为n的序列,要求找到一个字典序最小的子序列只包含1~k一次。
本题可以用单调栈解决,每当我们遍历到一个数
a
i
{a_i}
ai,如果当前数小于栈顶的元素并且存在
a
j
(
j
>
i
)
{a_j (j>i)}
aj(j>i)等于栈顶元素,那么我们就可以删除当前栈顶的元素,不断删除直到不符合条件为止,然后将当前元素入栈。
再用一个vis标记元素是否已经在栈里,如果当前元素已经在栈里,就不再需要入栈。
代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<unordered_set>
#include<unordered_map>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define lowbit(x) x&-x
const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=2e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int a[maxn],last[maxn],vis[maxn];
stack<int> sta;
int main()
{
int n,k;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++) scanf("%d",&a[i]),last[a[i]]=i;
for(int i=1;i<=n;i++)
{
if(vis[a[i]]) continue;
while (!sta.empty() && sta.top()>a[i] && i<last[sta.top()]) {
vis[sta.top()]=0; sta.pop();
}
sta.push(a[i]);
vis[a[i]]=1;
}
vector<int> p;
while (!sta.empty()) {
p.push_back(sta.top());
sta.pop();
}
reverse(p.begin(), p.end());
for(int i=0;i<p.size();i++) printf("%d ",p[i]);
}