PAT---A1129 Recommendation System (25分)

题意

输入n个用户搜索的商品,每输入一个商品,输出推荐的不超过k个商品,
推荐的算法是用户主动搜索次数多的排在前面,如果搜索次数相同则按照商品的id 升序排列。

思路

明显需要动态排序,数据结构用set,输入一个就重新将商品插入到set中,达到动态排序的效果。

Sample Input:

12 3
3 5 7 5 5 3 2 1 8 3 8 12

Sample Output:

5: 3
7: 3 5
5: 3 5 7
5: 5 3 7
3: 5 3 7
2: 5 3 7
1: 5 3 2
8: 5 3 1
3: 5 3 1
8: 3 5 1
12: 3 5 8
#include "bits/stdc++.h"
using namespace std;
struct Node{
    int id{};
    int cnt{0};
    bool operator < (const Node& o) const {
        if (o.cnt == cnt) return id < o.id;
        return cnt > o.cnt;
    }
};
int main(){
//     freopen("input.txt","r",stdin);
    int n, k; cin >> n >> k;
    set<Node> nodes;
    map<int,int> cnt;
    Node old = Node{};
    for (int i = 0; i < n; ++i) {
        int id;  scanf("%d",&id);
        if (!nodes.empty()) printf("%d: ",id);
        cnt[id] ++; int t = k; bool blank = false;
        for(auto& o:nodes){
            if (t-- == 0) break;
            if (blank) printf(" %d",o.id);
            else blank = true, printf("%d",o.id);
        }
        if(!nodes.empty()) printf("\n");
        old.id = id; old.cnt = cnt[id] - 1;
        auto it = nodes.find(old);
        if (it != nodes.end()) nodes.erase(it);
        nodes.insert(Node{id,cnt[id]});
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值