CodeForces - 1234B1 Social Network(queue容器+map容器)

题目链接: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zaiyang遇见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值