1. 程式人生 > 實用技巧 >C_pat_推薦系統(set模擬)

C_pat_推薦系統(set模擬)

方法一:set模擬

這裡如果用set模擬的話,需要對已經出現過的資料進行刪除,不然會重複輸出相同的商品 id;我們只是按照頻次排序,而不需要存重複的商品

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5;
int cnt[N];
struct node{
    int id, c;
    node(int pid=0, int cnt=0) {
        id = pid;
        c = cnt;
    }
    friend bool operator < (node a,node b){
        return a.c != b.c ? b.c < a.c : b.id > a.id; 
    }
};
int main() {
    int n,k,x; scanf("%d%d", &n, &k);
    set<node> s;
    for (int i=0; i<n; i++) {
        scanf("%d", &x);
        if (i) {
            printf("%d:", x);
            int j=0;
            for (auto it=s.begin(); it!=s.end() && j<k; it++) {
                printf(" %d", it->id);
                j++;
            }
            printf("\n");
        }
        auto it=s.find(node(x, cnt[x]));
        if (it!=s.end()) s.erase(it);
        s.insert(node(x, ++cnt[x]));
    }
    return 0;
}

複雜度分析

  • Time\(O(nlogn)\)
  • Space\(O(n)\)