本文主要是介绍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];elsereturn 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;
}
这篇关于1129. Recommendation System 解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!