2021-04-05

问题 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;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值