题意
输入n个用户搜索的商品,每输入一个商品,输出推荐的不超过k个商品,
推荐的算法是用户主动搜索次数多的排在前面,如果搜索次数相同则按照商品的id 升序排列。
思路
明显需要动态排序,数据结构用set,输入一个就重新将商品插入到set中,达到动态排序的效果。
Sample Input:
12 3
3 5 7 5 5 3 2 1 8 3 8 12
Sample Output:
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 "bits/stdc++.h"
using namespace std;
struct Node{
int id{};
int cnt{0};
bool operator < (const Node& o) const {
if (o.cnt == cnt) return id < o.id;
return cnt > o.cnt;
}
};
int main(){
// freopen("input.txt","r",stdin);
int n, k; cin >> n >> k;
set<Node> nodes;
map<int,int> cnt;
Node old = Node{};
for (int i = 0; i < n; ++i) {
int id; scanf("%d",&id);
if (!nodes.empty()) printf("%d: ",id);
cnt[id] ++; int t = k; bool blank = false;
for(auto& o:nodes){
if (t-- == 0) break;
if (blank) printf(" %d",o.id);
else blank = true, printf("%d",o.id);
}
if(!nodes.empty()) printf("\n");
old.id = id; old.cnt = cnt[id] - 1;
auto it = nodes.find(old);
if (it != nodes.end()) nodes.erase(it);
nodes.insert(Node{id,cnt[id]});
}
}