题目链接:点击进入
题目
题意
一个长度 n 的数组,问此数组是否有一个长为 k 的子序列同时这个子序列 1 - k 都出现且仅出现一次,同时要求这个子序列字典序最小,输出此子序列
思路
记录每个数最后出现的位置,从 1 - n 枚举数组,如果 a [ i ] 在栈里出现过跳过看 a [ i + 1 ] ,如果没有出现过,将 a [ i ] 与栈顶元素相比较,如果栈顶元素比 a [ i ] 大,同时 a [ i ] 位置后边还有栈顶元素,那么删去栈顶元素接着比较,直到在栈中找不到满足条件的栈顶或者栈空,此时将 a [ i ] 入栈,枚举下一个数。最后枚举结束,将栈中答案倒序输出即为答案。
代码
#include<iostream>
#include<string>
#include<map>
#include<set>
#include<stack>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int N=2e4+10;
const int mod=1e9+7;
const double eps=1e-12;
const int maxn=1e6+10;
int n,k,x[maxn],last[maxn],ans[maxn],cnt;
bool vis[maxn];
stack<int>st;
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);cout.tie(0);
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d",&x[i]);
for(int i=1;i<=n;i++)
if(last[x[i]]<i)
last[x[i]]=i;
for(int i=1;i<=n;i++)
{
if(vis[x[i]]) continue;
while(st.size()&&last[st.top()]>i&&x[i]<=st.top())
{
vis[st.top()]=0;
st.pop();
}
if(!vis[x[i]])
{
vis[x[i]]=1;
st.push(x[i]);
}
}
while(st.size())
{
ans[cnt++]=st.top();
st.pop();
}
for(int i=cnt-1;i>=0;i--)
printf("%d ",ans[i]);
return 0;
}