其他分享
首页 > 其他分享> > 推荐系统

推荐系统

作者:互联网

https://www.acwing.com/problem/content/1624/

写法1

#include <iostream>
#include <cstring>
#include <algorithm>
#include <set>

using namespace std;

struct node
{
    int value, cnt;
    bool operator < (const node& t) const
    {
        return (cnt != t.cnt) ? cnt > t.cnt : value < t.value;
    }
};

int n, k, num;
int book[50001];//记录访问频次

int main()
{
    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;
}

写法2

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 50010;

int n, m;
int cnt[N];
int top_k[11];

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;
}

标签:cnt,int,推荐,系统,++,num,include,top
来源: https://www.cnblogs.com/xjtfate/p/16615880.html