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)\)
原文地址:https://www.cnblogs.com/wdt1/p/13658409.html