PAT甲级1129 Recommendation System (25分)|C++实现

一、题目描述

原题链接
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:

在这里插入图片描述

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

二、解题思路

对于每个输入的数,找出它前面出现次数前三的数(如果前面的数不超过三个,则输出有的所有数)。我们可以用cnt数组表示每个数出现的次数,将新的数字插入之后进行排序,详情见代码注释即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 50010;
int cnt[maxn] = {0};
bool flag[maxn] = {false};
bool cmp(int a, int b)  //按照出现的次数排序,如果出现的次数相同,则按照自身大小从小到大排序
{
  if(cnt[a] != cnt[b])	return cnt[a] > cnt[b];
  else	return a < b;
}
int main()
{
  int N, K, tmp;
  vector<int> ans;
  scanf("%d%d", &N, &K);
  scanf("%d", &tmp);
  ans.push_back(tmp);
  cnt[tmp]++;
  flag[tmp] = true;
  for(int i=1; i<N; i++)
  {
    scanf("%d", &tmp);
    printf("%d:", tmp);
    int sze = ans.size();
    sze = min(sze, K);
    for(int j=0; j<sze; j++)
      printf(" %d", ans[j]);    //遍历输出
    printf("\n");
    if(!flag[tmp])  //是新出现的数
    {
      ans.push_back(tmp);
      flag[tmp] = true;
    }
   	cnt[tmp]++;
    sort(ans.begin(), ans.end(), cmp);//必须插入之后排序
    if(ans.size() == K+1)
    {
      flag[ans[K]] = false; //将最后一个数设为未访问过的
      ans.pop_back();   //弹出最后一个数
    }
  }
  return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值