写在前面

  • 思路分析
  • 正确理解题意
  • 根据用户每次点击的东西的编号,输出他在点当前编号之前应该给这个用户推荐的商品的编号
  • 只推荐k个
  • 如果恰好两个商品有相同的点击次数,就输出编号较小的那个
  • 具体实现
  • 结构体封装商品属性:编号value和出现次数cnt,重载小于号,使<根据set中node的cnt排序,如果cnt相等就按照node的value排序
  • 封装数据至​​set<node>​
  • 根据大小自动排序,即按照出现次数排序好商品node,每次输出set的前k个node的value值即可
  • 当i != 0时候开始输出,因为i==0时候用户才第1次点击,没有可以推荐的
  • book[num]标记num出现的次数,每次寻找set中当前值为num和次数为book[num]的那个值,找到则移除然后更新元素出现次数
  • 题目有一定难度,学习ing
  • 知识点新应用

测试用例

input:
12 3
3 5 7 5 5 3 2 1 8 3 8 12
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

ac代码

#include <iostream>
#include <set>
using namespace std;
int book[50001];
struct node
{
int value, cnt;
bool operator < (const node &a) const
{
return (cnt != a.cnt) ? cnt > a.cnt : value < a.value;
}
};
int main()
{
int n, k, num;
scanf("%d%d", &n, &k);
set<node> s;

for (int i = 0; i < n; i++)
{
scanf("%d", &num);
// 先循环输出,然后插入值进行次数等更新(根据点击历史推荐)
if (i != 0)
{
printf("%d:", num);
int tmpCnt = 0;
for(auto it = s.begin(); tmpCnt < k && it != s.end(); it++)
{
printf(" %d", it->value);
tmpCnt++;
}
printf("\n");
}
// 当前集合已存在num值,先删除,更新发现次数
auto it = s.find(node{num, book[num]});
if (it != s.end()) s.erase(it);
book[num]++;
// 更新插入次数
s.insert(node{num, book[num]});
}
return 0;
}

知识点小结

// 集合迭代遍历
set<node> s;
for(auto it = s.begin(); tmpCnt < k && it != s.end(); it++)

// 集合元素查找
auto it = s.find(node{num, book[num]});

// 结构体运算符重载
struct node
{
int value, cnt;
bool operator < (const node &a) const
{
return (cnt != a.cnt) ? cnt > a.cnt : value < a.value;
}
};