技巧总结
对于数值对,一个升序,一个降序,利用结构体存储,重载比较函数即可实现(多数值排序同理)
题目描述
解题思路
- 数据范围不大,所以可以利用数组下标进行计数
- 对于数值对,采用结构体存储,重载比较函数,进行排序
代码实现
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int a[N];
struct data
{
int n;
int c;
bool operator< (const data& t) const // 重载比较函数使其对次数降序,数值升序
{
if(c != t.c) return c > t.c;
else return n < t.n;
}
}s[N];
int main()
{
int n;
cin >> n;
int x = 0;
for (int i = 0; i < n; i ++)
{
cin >> x;
a[x] ++; // 利用哈希表的性质利用下标进行计数
}
int cnt = 0;
for (int i = 0; i < N; i ++) // 注意这里是N
{
if (a[i])
{
s[cnt ++ ] = {i, a[i]}; // 将(数字,数字出现的次数)存储到结构体中
}
}
sort(s, s + cnt);
for (int i = 0; i < cnt; i ++)
{
cout << s[i].n << " " << s[i].c << endl;
}
return 0;
}