一、题目描述
原题链接
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;
}