A1129 Recommendation System (25 point(s))

Set的应用--值不重复,值的个数增加

1. 原文

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:

1
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:

1
2
12 3
3 5 7 5 5 3 2 1 8 3 8 12

Sample output:

1
2
3
4
5
6
7
8
9
10
11
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

2. 解析

结构体内按个数降序排列,个数相同时按值升序。

每次更新,删除set值已存在的值,个数+1,再插入set

1
2
3
4
5
6
7
8
  set<node>::iterator t=s.find(temp);
if (t!=s.end())
{
s.erase(t);
}
total[a]++;
temp.cnt=total[a];
s.insert(temp);

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<cstdio>
#include<set>
using namespace std;
struct node
{
int value,cnt;
bool operator < (const node &a) const{
if(cnt!=a.cnt){
return cnt>a.cnt;
}else{
return value<a.value;
}
}
};
set<node> s;
int total[50010]={};
int main()
{
int n,k;
scanf("%d%d",&n,&k);
int a;
for (int i = 0; i < n; ++i)
{
scanf("%d",&a);
int cnt=0;
if (i>0)
{
printf("%d:", a);
for (set<node>::iterator t = s.begin(); t != s.end()&&cnt<k; ++t)
{
printf(" %d",t->value);
cnt++;
}
printf("\n");
}
node temp;
temp.value=a;
temp.cnt=total[a];
set<node>::iterator t=s.find(temp);
if (t!=s.end())
{
s.erase(t);
}
total[a]++;
temp.cnt=total[a];
s.insert(temp);
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1129/
  • 发布时间: 2019-09-03 00:47
  • 更新时间: 2021-10-29 14:09
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!