PAT Advanced 1129 Recommendation System (25 )

题目描述

在这里插入图片描述

Input Specification:

在这里插入图片描述

Output Specification:

在这里插入图片描述

Sample Input:

在这里插入图片描述

Sample Output:

在这里插入图片描述

解题思路

快乐模拟,终于快乐了一回。。一开始想着用啥优先队列的,无奈一直想不出怎么写排序方法,想着暴力那点分,结果就过了,看来是我想复杂了。。因为暴力的时间复杂度差不多是O(M*nlogn),M<5e4, n<10。所以实在想不出好方法的时候,暴破也是一种方法。。

Code

  • AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e4+10;
int cnt[maxn], vis[maxn];
bool cmp(const int &a, const int &b) {
	return cnt[a] != cnt[b] ? cnt[a] > cnt[b] : a < b;
}
int main() {
	//freopen("in.txt", "r", stdin);
	int N, K, pre = -1, temp;
	cin >> N >> K;
	vector<int> res;
	for(int i = 0; i<N; i++) {
		cin >> temp;
		if(pre != -1) {
			if(!vis[pre] && res.size() < K) {
				res.push_back(pre);
				vis[pre] = 1;
			} else if(!vis[pre] && cnt[res[K-1]] < cnt[pre]) {
				vis[res[K-1]] = 0;
				vis[pre] = 1;
				res[K-1] = pre;
			} else if(!vis[pre] && cnt[res[K-1]] == cnt[pre] && pre < res[K-1]) {
				vis[res[K-1]] = 0;
				vis[pre] = 1;
				res[K-1] = pre;
			}
			sort(res.begin(), res.end(), cmp);
			cout << temp << ": ";
			for(int j = 0; j<res.size(); j++) {
				cout << res[j];
				j != res.size()-1 ? cout << ' ' : cout << '\n';
			}
		}
		cnt[temp]++;
		pre = temp;
	}
	
	return 0;
}

总结

所以实在想不出好方法的时候,暴破也是一种方法。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值