问题 J: One of Each
题目描述
You are given a sequence of n integers x = [x1,x2,...,xn] and an integer k . It is guaranteed that 1 ≤ xi ≤ k , and every integer from 1 to k appears in the list x at least once.
Find the lexicographically smallest subsequence of x that contains each integer from 1 to k exactly once.
输入
The first line of input contains two integers n and k ( 1 ≤ k ≤ n ≤ 2 ∙105), where n is the size of the sequence, and the sequence consists only of integers from 1 to k .
Each of the
输出
Output a sequence of integers on a single line, separated by spaces. This is the lexicographically smallest subsequence of X that contains every value from 1 to k.
next n lines contains a single integer xi( 1 ≤ xi ≤ k ). These are the values of the sequence X in order. It is guaranteed that every value from 1 to k will appear at least once in the sequence X .
样例输入
【样例1】 6 3 3 2 1 3 1 3 【样例2】 10 5 5 4 3 2 1 4 1 1 5 5
样例输出
【样例1】 2 1 3 【样例2】 3 2 1 4 5
贪心思路是错误的,并不一定是第一个1234...n出现的那种组合
最重要的是按照字典序,请注意,从头部添加,所以,back才是输出的开始,
如果此时的number已经出现在deque里面了,那么就要去while处理,while处理很关键的就是判断cnt,也就是如果后面还有这个数,那么就选后面的,此时的就可以pop
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int cnt[200005];
int vis[200005];
int a[200005];
deque<int>dq;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",a+i);
cnt[a[i]]++;
}
for(int i=1;i<=n;i++)
{
cnt[a[i]]--;
if(!vis[a[i]])
{
vis[a[i]]=1;
while(!dq.empty()&&dq.front()>a[i]&&cnt[dq.front()])///保证头最小
{
vis[dq.front()]=0;
dq.pop_front();
}
dq.push_front(a[i]);
}
}
while(!dq.empty())
{
cout<<dq.back()<<" ";
dq.pop_back();
}
return 0;
}