问题描述
给定n个整数,请统计出每个整数出现的次数,按出现次数从多到少的顺序输出。
输入格式
输入的第一行包含一个整数n,表示给定数字的个数。
第二行包含n个整数,相邻的整数之间用一个空格分隔,表示所给定的整数。
输出格式
输出多行,每行包含两个整数,分别表示一个给定的整数和它出现的次数。按出现次数递减的顺序输出。如果两个整数出现的次数一样多,则先输出值较小的,然后输出值较大的。
样例输入
12
5 2 3 3 1 3 4 2 5 2 3 5
样例输出
3 4
2 3
5 3
1 1
4 1
评测用例规模与约定
1 ≤ n ≤ 1000,给出的数都是不超过1000的非负整数。
我们建立一个map<int,int>对象,键存整数类型,值存数字出现的次数,然后统计到map数组里面之后,我们采用优先级队列来对map进行排序,由于优先级队列是大跟堆,从大到小,所以我们书写一个排序规则,就可以解决此题。
#include <iostream>
#include<queue>
#include<cstdio>
#include<map>
using namespace std;
struct tmp {
int x, y;
bool operator<(const tmp& a) const {
if (y != a.y)
return y < a.y;
else
return x > a.x;
}
};
int main()
{
int n;
int x;
cin >> n;
map<int, int>m;
for (int i = 0; i < n; i++) {
cin >> x;
if (m.count(x)==0) {
m[x] = 1;
}
else {
m[x]++;
}
}
priority_queue<tmp>p;
map<int, int>::iterator it;
for (it = m.begin(); it != m.end(); it++) {
tmp g;
g.x = it->first, g.y = it->second;
p.push(g);
}
while (!p.empty()) {
cout << p.top().x << " " << p.top().y<< endl;
p.pop();
}
return 0;
}
本文介绍了一种使用C++实现的算法,该算法能够接收一组整数,统计每个整数的出现频率,并按频率从高到低,频率相同时数值从小到大的顺序输出整数及其频次。通过map和优先级队列的数据结构,实现了高效的统计和排序。
231

被折叠的 条评论
为什么被折叠?



