• c_pat_推荐系统(set模拟)


    方法一:set模拟

    这里如果用set模拟的话,需要对已经出现过的数据进行删除(因为set是通过对比id和c来确定是否为一个对象的,所以删除时必要的),不然会重复输出相同的商品 id;

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int N=5e5+5;
    
    int cnt[N];
    struct node {
        int id, c;
        bool operator < (node p) const {
            if (c!=p.c) return c>p.c;
            return id<p.id;
        }
    };
    struct cmp{
        bool operator()(node& a, node& b){
            if (a.c!=b.c) return a.c>b.c;
            return a.id<b.id;
        }
    };
    int main() {
        std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
        int n,k; cin>>n>>k;
        set<node> st;
    
        for (int i=0; i<n; i++) {
            int x; cin>>x;
            if (i>0) {
                int j=0;
                printf("%d:", x);
                for (auto it=st.begin(); it!=st.end() && j<k; it++, j++) {
                    printf(" %d", it->id);
                }
                printf("\n");
            }
            st.erase({x,cnt[x]++});    //找的时候因为要组合查找,所以你还差一个频次
            st.insert({x,cnt[x]});
        }
        return 0;
    }
    

    复杂度分析

    • Time\(O(nlogn)\)
    • Space\(O(n)\)
  • 相关阅读:
    CVS,GIT,Mercurial和SVN比较
    ubuntu-使用终端配置网络
    编写简单的hashCode方法
    编写高质量equals方法
    文件上传和下载
    Java常用命令
    增删查改-MySQL
    Newton迭代法-C++
    二分法-C++
    适配器模式
  • 原文地址:https://www.cnblogs.com/wdt1/p/13658409.html
Copyright © 2020-2023  润新知