Recommendation system predicts the preference that a user would give to an item. Now you are asked to program a very simple recommendation system that rates the user‘s preference by the number of times that an item has been accessed by this user.
Input Specification:
Each input file contains one test case. For each test case, the first line contains two positive integers: N (≤ 50,000), the total number of queries, and K (≤ 10), the maximum number of recommendations the system must show to the user. Then given in the second line are the indices of items that the user is accessing -- for the sake of simplicity, all the items are indexed from 1 to N. All the numbers in a line are separated by a space.
Output Specification:
For each case, process the queries one by one. Output the recommendations for each query in a line in the format:
query: rec[1] rec[2] ... rec[K]
where query
is the item that the user is accessing, and rec[i]
(i
=1, ... K) is the i
-th item that the system recommends to the user. The first K items that have been accessed most frequently are supposed to be recommended in non-increasing order of their frequencies. If there is a tie, the items will be ordered by their indices in increasing order.
Note: there is no output for the first item since it is impossible to give any recommendation at the time. It is guaranteed to have the output for at least one query.
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
1 //题目大意:就是顾客买东西之前,根据顾客的购买历史进行商品推荐 2 //所以购买第一件商品3是没有推荐的,因为没有购买历史记录 3 //然后根据前面购买的历史次数,进行次数从多到少进行推荐,最多推荐三个,相同次数的推荐标号最小的的// 4 //使用set来得到按要求的排序规格,vector来辅助查询set中是否已经存在元素 5 #include <iostream> 6 #include <set> 7 #include <vector> 8 using namespace std; 9 int n, k; 10 struct Node 11 { 12 int value, cnt; 13 bool operator < (const Node& a)const//set的排序规则 14 { 15 return (cnt != a.cnt) ? cnt > a.cnt:value < a.value; 16 } 17 }; 18 int main() 19 { 20 int n, k, num; 21 scanf("%d %d", &n, &k); 22 set<Node>s; 23 vector<int>v(n + 1, 0); 24 for (int i = 0; i < n; ++i) 25 { 26 cin >> num; 27 if (i != 0)//第一件商品没有推荐 28 { 29 cout << num << ":"; 30 int i = 1; 31 for (auto ptr = s.begin(); ptr != s.end() && i <= k; ++ptr, i++) 32 cout << " " << ptr->value; 33 cout << endl; 34 } 35 auto ptr = s.find(Node{ num,v[num] }); 36 if (ptr != s.end())//记住set不能修改内容,只能擦除后重新写入 37 s.erase(ptr); 38 v[num]++; 39 s.insert(Node{ num,v[num] });//使用了初始化列表原则 40 } 41 return 0; 42 }
原文地址:https://www.cnblogs.com/zzw1024/p/11483142.html