#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;
typedef struct Node
{
int data, times;
Node(int a, int b)
{
data = a, times = b;
}
}Node;
const int MAX = 5e4+10;
int N, K;
int A[MAX];
int T[MAX] = {0};//表示每个数字出现的次数
vector<Node> V;//在队列中的元素
bool cmp(Node A, Node B)
{
if(A.times != B.times) return A.times > B.times;
return A.data < B.data;
}
int main()
{
scanf("%d %d", &N, &K);
for(int i=0; i<N; i++) scanf("%d", &A[i]);
for(int i=1; i<N; i++)
{
T[A[i-1]]++;
int k=0;
while(k < V.size() && V[k].data != A[i-1]) k++;//查询是否已经在队列中
if(k != V.size()) V[k].times++;//已在,则其次数+1
else
{
if(V.size() < K) V.push_back(Node(A[i-1], T[A[i-1]]));//否则若队列未满则直接加入
else if(T[A[i-1]] > V[V.size()-1].times//或者出现次数比最后一个多,或者出现次数相同,但其数据更小,则替换
|| (T[A[i-1]] == V[V.size()-1].times && A[i-1] < V[V.size()-1].data))
{
V.pop_back();
V.push_back(Node(A[i-1], T[A[i-1]]));
}
}
sort(V.begin(), V.end(), cmp);//排序后输出
printf("%d:", A[i]);
for(int i=0; i<V.size(); i++) printf(" %d", V[i]);
printf("\n");
}
return 0;
}
PAT (Advanced Level) Practice A1129 Recommendation System (25 分)(C++)(甲级)(队列思想、排序)
最新推荐文章于 2019-09-04 16:23:38 发布