CF1234 B2 题解
好的这道题应该太水了没有人看 Orz。
介绍一下 STL queue
。
queue
queue<type A> q
代表队列。这种东西有两种操作:
- 插入。在 STL 中表示为
q.push(x)
。 - 删除。在 STL 中表示为
q.pop()
。
这是一种先进先出的数据结构。
就比如食堂打饭(都烂掉了这例子……),队首的人打完就走,后面的人从队尾进入。这就是队列。
所以,这里要用到 queue
是因为,进来时是在顶端,末端删除。
然后怎么判重?我们需要用到 map
。
map
map<type A, type B> m
代表映射。它其实用起来和数组没什么区别,但是有一点需要注意:在 m[a] = b
中,
a
a
a 一定是
A
A
A 类,
b
b
b 一定是
B
B
B 类。
于是,我们需要这么做:
map<string, int> m;
m["apple"] = 2;
m["pear"] = 3;
这里判重可以让 map[a]++
,如果 map[a] = 0
就说明没有。
Code:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, k;
cin >> n >> k;
map<int, int> m;
queue<int> q;
for(int i = 0;i < n;i++){
int a;
cin >> a;
if(m[a] == 0){
if(q.size() == k){
m[q.front()]--;
q.pop();
}
q.push(a);
m[a]++;
}
}
vector<int> ans;
while(!q.empty()){
ans.push_back(q.front());
q.pop();
}
cout << ans.size() << endl;
reverse(ans.begin(), ans.end());
for(int i = 0;i < ans.size();i++){
cout << ans[i] << " ";
}
return 0;
}