题目链接:https://vjudge.net/contest/331024#problem/B
Input
7 2
1 2 3 2 1 3 2
Output
2
2 1
Input
10 4
2 3 3 1 1 2 1 2 3 3
Output
3
1 3 2
In the first example the list of conversations will change in the following way (in order from the first to last message):
[];
[1];
[2,1];
[3,2];
[3,2];
[1,3];
[1,3];
[2,1].
In the second example the list of conversations will change in the following way:
[];
[2];
[3,2];
[3,2];
[1,3,2];
and then the list will not change till the end
翻译:
先输入一个n和m,接下来n个数,m表示容器的大小。
对于每一个数,若没有在容器里,就加入容器。
容器里若有这个数,就直接跳过去。
若容器已满,但这个数没有在容器里,就把最先输入的数弹出一个。
分析:
很明显的queue容器
queue容器的知识点:
先进先出,元素的插入只能在队尾,元素的删除只能在队首。
入队–>push()
出队–>pop()
队首元素—>front()
队尾元素—>back()
队列是否为空—>empty()
队列中的元素数目—>size()
代码:
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
int n,k,a[200001];
while(~scanf("%d%d",&n,&k))
{
map<int,int>Q;
int v=1,b[200002]={0};
for(int i=0; i<n; i++)scanf("%d",&a[i]);
memcpy(b,a,sizeof(a));
sort(b,b+n);
Q[b[0]]=v;
for(int i=1; i<n; i++)
{
if(b[i]!=b[i-1])
{
v++;
Q[b[i]]=v;
}
Q[b[i]]=v;
}
int book[200001];
memset(book,0,sizeof(book));
queue<int>q;
q.push(a[0]);
book[Q[a[0]]]=1;
for(int i=1; i<n; i++)
{
if(book[Q[a[i]]])
continue;
else
{
if(q.size()<k)
{
q.push(a[i]);
book[Q[a[i]]]=1;
}
else
{
book[Q[q.front()]]=0;
q.pop();
q.push(a[i]);
book[Q[a[i]]]=1;
}
}
}
int a[200002]= {0},k=0;
printf("%d\n",q.size());
while(!q.empty())
{
a[k++]=q.front();
q.pop();
}
printf("%d",a[k-1]);
for(int i=k-2; i>=0; i--)
printf(" %d",a[i]);
printf("\n");
}
return 0;
}