PAT(A)-1129. Recommendation System (25)(优先队列)

记录一个菜逼的成长。。

题目链接

题目大意:
给你n个数和k大小的空间。
在每次访问第i个数之前,先输出第i个数之前k个按出现次数从大到小排列后的数,如果次数相同则按数的大小从小到大输出。

用一个优先队列来维护,每次输出前k个。
几个数组:
vis[i] := 表示i是否在前k个输出的数里
use[i] := 表示i是否之前出现过。
对于每一个访问的数(除了第一个),先输出前k个,不满k个则全输出。保存在一个中间数组里。
之后再对访问的数进行计数,如果之前没访问过的放进优先队列
如果之前访问过了,但是没在输出的数了,对优先队列进行出队操作,直到这个数出队。
然后再将中间数组里的数放进优先队列。

原来想把代码写好看点。。然而总有点过不了,最后直接暴力了一发。。
代码略丑。。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 50000 + 10;
int cnt[maxn],vis[maxn],use[maxn];
struct cmp{
    bool operator()(const int &a,const int &b)const{
        if(cnt[a] != cnt[b])return cnt[a] < cnt[b];
        return a > b;
    }
};
priority_queue<int,vector<int>,cmp>q;
int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k)){
        vector<int>tmp;
        for( int i = 0,x; i < n; i++ ){
            scanf("%d",&x);
            int c = 0;
            if(i){
                printf("%d:",x);
                while(c < k && !q.empty()){
                    int t = q.top();
                    vis[t] = 1;
                    tmp.push_back(t);
                    printf(" %d",t);
                    q.pop();c++;
                }
                puts("");
            }
            cnt[x]++;
            if(!use[x]){
                use[x] = 1;
                q.push(x);
            }
            else {
                if(!vis[x]){
                    while(q.top() != x){
                        tmp.push_back(q.top());q.pop();
                    }
                    tmp.push_back(q.top());q.pop();
                }
            }   
            for( int i = 0; i < tmp.size(); i++ )
                q.push(tmp[i]),vis[tmp[i]] = 0;
            tmp.clear();
        }

    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值