牛客 Early Orders

题目链接:https://ac.nowcoder.com/acm/problem/218908

题意:给定 n个元素 元素值不超过k  要求 字典序最小的子序列  使得每个元素只出现过一次 (保证1~k每个元素出现至少一次)

思路:类似单调栈一样  一直比较栈顶元素s和当前元素x 当s>x 且s不是最后一个同值元素时 

就把s出栈,因为这样取后一个s' 时 会更优  当不合法时 才把x放入栈顶 然后继续比较

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=2e5+10;
 4 const int mod=1e9+7;
 5 #define ll long long
 6 #define ull unsigned long long
 7 #define pb push_back
 8 #define pi pair<int,int>
 9 #define fi first
10 #define sc second
11 
12 int st[maxn];
13 int cnt[maxn];
14 int a[maxn];
15 
16 
17 int main()
18 {
19     ios::sync_with_stdio(0);
20     cin.tie(0);
21     int n,k;
22     cin>>n>>k;
23     for(int i=1;i<=n;i++) cin>>a[i],cnt[a[i]]++;
24 
25     stack<int>s;
26     for(int i=1;i<=n;i++)
27     {
28         int x=a[i];
29         cnt[x]--;
30         if(st[x]) continue;
31         while(!s.empty())
32         {
33             int u=s.top();
34             if(u<x||!cnt[u]) break;
35             st[u]=0;
36             s.pop();
37         }
38         st[x]=1;
39         s.push(x);
40     }
41     vector<int>ans;
42     while(!s.empty())
43     {
44         ans.pb(s.top());
45         s.pop();
46     }
47     reverse(ans.begin(),ans.end());
48     for(auto &v:ans) cout<<v<<  " ";
49     cout<<'\n';
50 
51 
52 
53 
54 
55 }
View Code

 

    

posted @ 2021-03-26 09:55  canwinfor  阅读(44)  评论(0)    收藏  举报