1129. Recommendation System 解析

按输入的次数排序,现实前k位的数字。

注意一点,只有记录里面没有的数字才能丢到提示数组里面,最后一个CASE就是测都是重复数的情况。





#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
int n, k;

int VisCount[50010];
int rec[15];


bool cmp(int n1, int n2) {
	
	if (VisCount[n1] != VisCount[n2])
		return VisCount[n1] > VisCount[n2];
	else
		return n1 < n2;
}

int main() {
	cin >> n >> k;

	memset(VisCount, 0, sizeof(VisCount));
	memset(rec, 0, sizeof(rec));
	VisCount[0] = -1;//保证0排在后面
	
	int num;
	int pos = 1;
	for (int i = 1; i <= n; i++) {
		cin >> num;
		bool isFull = false;//又没有放满k个数
		
		sort(rec + 1, rec + k + 1, cmp);//排序

		if (i > 1) {
			cout << num << ":";
			for (int j = 1; j <= k; j++) {
				if (rec[j] != 0) {
					cout << " " << rec[j];
				}
			}
			cout << endl;
		}

		VisCount[num]++;

		bool isFind = false;//查询,rec里面是否已经有该数
		for (int i = 1; i <= k; i++) {
			if (rec[i] == num)
				isFind = true;
		}

		if (!isFind && pos < k && !isFull) {//没有满丢进去
			rec[pos++] = num;
		}
		else {//满了或者刚满(最后一个没有加进去)
			bool tag = true;
			if (!isFind && rec[pos] == 0) {//(最后一个没有加进去)
				rec[pos] = num;
				isFull = true;
				tag = false;
			}			

			if (tag && !isFind) {
				if (VisCount[num] > VisCount[rec[k]])
					rec[k] = num;
				else if (VisCount[num] == VisCount[rec[k]])
					rec[k] = min(num, rec[k]);
			}				
		}
	}

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值