题意:对于每个数字,统计排在它前面的各个数字出现的次数,按出现次数的多少输出。
思路:设置一个结构体,保存一个数的值、这个数出现的次数。利用set
自动有序这一特性(set底层为红黑树),我们可以让set
自动对这些结构体进行排序,只需在结构体中描述结构体的排序规则:
struct node {
int val, count;
friend bool operator < (node n1, node n2) {
if(n1.count != n2.count)
return n1.count > n2.count;
else return n1.val < n2.val;
}
};
对于给出的序列,我们从前往后遍历。对于一个数,如果它已经存在于设置的set
中,我们将它移除,之后令这个结构体的计数count ++
,最后再将它重新放回set
中。(移除、重新插入操作是为了更新这个结构体的排序位置)
#include<cstdio>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
struct node {
int val, count;
friend bool operator < (node n1, node n2) {
if(n1.count != n2.count)
return n1.count > n2.count;
else return n1.val < n2.val;
}
}table[50001];
set<node> orderByTimes;
int queryNum, recNum;
int main() {
scanf("%d %d", &queryNum, &recNum);
for (int i = 1;i <= queryNum;i ) {
table[i].val = i;
}
for (int i = 0;i < queryNum;i ) {
int temp;
scanf("%d", &temp);
if (i > 0) {
printf("%d:", temp);
int count = 0;
for (auto it = orderByTimes.begin();it != orderByTimes.end() && count < recNum;it ) {
printf(" %d", *it);
count ;
}
if (orderByTimes.find(table[temp]) != orderByTimes.end()) {
orderByTimes.erase(table[temp]);
}
printf("\n");
}
table[temp].count ;
orderByTimes.insert(table[temp]);
}
}