PAT甲级真题1129 推荐系统(好模拟两种办法)

推荐系统可以预测用户对某项商品的偏好。

现在,请你编写一个非常简单的推荐系统,该系统通过分析用户对各种商品的访问次数来预测用户的偏好。

补充
用户会进行 NN 次商品访问,每次访问某件商品之前,系统需要给用户推荐最多不超过 KK 件商品。

而推荐的这 KK 件商品,应该是在本次访问之前的所有访问中,被访问次数最多的 KK 件商品。

当然,用户在进行第一次访问时,无法给出任何推荐,因为此时所有商品的被访问次数都为 00。

输入格式
第一行包含两个正整数: NN,表示用户访问商品次数,KK 表示系统提供给用户的最大推荐数。

第二行给出用户正在访问的商品编号。

所有商品编号 1∼N1∼N。

输出格式
对于每次访问,以如下格式,输出一行建议:

query: rec[1] rec[2] … rec[K]
其中,query 表示用户正在访问的商品,rec[i] 是推荐系统推荐给用户的第 ii 个商品。

应当以频率从高到低的顺序推荐访问频率最高的前 KK 个商品。

对于访问频率相同的商品,优先推荐商品编号小的。

注意:对于第一次访问没有任何输出,因为无法给出建议。

数据范围
1≤N≤500001≤N≤50000
1≤K≤101≤K≤10
输入样例:
12 3
3 5 7 5 5 3 2 1 8 3 8 12
输出样例:
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 <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 50010;

int n, m;
int cnt[N];
int top_k[N];
int k=0;
int main()
{
    scanf("%d%d", &n, &m);

    int k = 0;
    for (int i = 0; i < n; i ++ )
    {
        int id;
        scanf("%d", &id);
        if(i){
            printf("%d:", id);
            for (int j = 0; j < k; j ++ ) printf(" %d", top_k[j]);
            puts("");
        } 
        cnt[id]++;
       bool exists = false;
        for (int j = 0; j < k; j ++ )
            if (top_k[j] == id)
            {
                exists = true;
                break;
            }
        if (!exists) top_k[k ++ ] = id;
        sort(top_k,top_k+k,[](int x,int y){
        	if(cnt[x]!=cnt[y])return cnt[x]>cnt[y];
        	return x<y;
        });
        k=min(k,m);
    }
      return 0;
}
        
#include <cstdio>
#include <set>
using namespace std;
int book[50001];
struct node {
    int value, cnt;
    node(int a, int b):value(a), cnt(b){}
    bool operator < (const node &a) const {
        return (cnt != a.cnt) ? cnt > a.cnt : value < a.value;
    }
};
int main() {
    int n, k, num;
    scanf("%d%d", &n, &k);
    set<node> s;
    for (int i = 0; i < n; i++) {
        scanf("%d", &num);
        if (i != 0) {
            printf("%d:", num);
            int tempCnt = 0;
            for(auto it = s.begin(); tempCnt < k && it != s.end(); it++) {
                printf(" %d", it->value);
                tempCnt++;
            }
            printf("\n");
        }
        auto it = s.find(node(num, book[num]));
        if (it != s.end()) s.erase(it);
        book[num]++;
        s.insert(node(num, book[num]));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小王子y

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

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

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

打赏作者

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

抵扣说明:

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

余额充值