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-N,给出用户按时间顺序访问的对象序列,以及每次最多推荐的对象个数,在每次用户访问对象前(除第一次)给出推荐序列,按照先前访问次数降序排列,如果访问次数一致,按照序号升序排列。
这勾八题目我读了半天,谁来救救我的英蓝瓜哥。没有想太多,只知道每次都需要选出访问次数最高的
个对象,每次排序估计时间开销太大。于是乎我打算用set和vector设计一个桶vector<set<int>> item(n+1)
,那么item[i]
就表示访问次数为
的对象集合,set会自动按照序号升序排列。接着再用一个vector<int> cnt(n+1,0)
存储每个物体的访问次数。那么每当一个对象的访问次数增加时,我们都需要将原先桶中(
)的对象erase,在新桶中(
)插入。然后再用一个most变量记录当前的最高访问次数,那么每次选择推荐对象时都从
开始找
个即可。
⚠️如果访问过的对象不足 个就不需要推荐这么多,有多少就推荐多少。
听上去虽然有点麻烦,但实现起来还是很快的。然鹅一开始最后一个测试点一直SF,我一脸茫然,两眼懵逼。最后发现前面的访问对象可能都是同一个,那么预测对象只需要输出一个即可,而不能取决于访问次数!!!
还有一种做法,感觉相对easy点,就是全部装在一个set中,然后给出set的compare函数,那么每次都直接从前 个选择,感觉实操性更强一点。
o还无意中发现,multiset中如果erase函数的参数给的是特定值的话就会把所有特定值都删掉,如果想只删其中一个,就搭配find给出迭代器:multiset.erase(multiset.find(value))
。估计内部实现就是set<pair<...,int>>
。
🐎
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
int n, k, m, most = 1, j, p, distinct = 1;
cin >> n >> k >> m;
vector<set<int>> item(n + 1);
vector<int> cnt(n + 1, 0);
item[1].insert(m), cnt[m] = 1;
for (int i = 1; i < n; ++i)
{
cin >> m;
j = min(distinct, k), p = most;
printf("%d:", m);
while (j > 0)
for (auto &t: item[p--])
{
printf(" %d", t);
if (--j <= 0) break;
}
printf("\n");
if (++cnt[m] > 1) item[cnt[m] - 1].erase(m);
else ++distinct;
item[cnt[m]].insert(m);
most = max(most, cnt[m]);
}
}