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;
}
总结
所以实在想不出好方法的时候,暴破也是一种方法。。