CCF CSP题解:数字排序(201503-2)

链接和思路

OJ链接:传送门

本文需求来自LA姐。本题仅需用一个辅助数据结构Tmp记录每1个数字的值(value)及其出现的次数(cnt),然后重载运算符<并针对cnt排序输出即可。辅助数据结构Tmp定义如下:

cpp 复制代码
struct Tmp {
    int value;
    int cnt;

    bool operator<(const Tmp &t) const {
        if (this->cnt != t.cnt)
            return this->cnt < t.cnt;
        return this->value > t.value;
    }
} result[1005];

其余见AC代码。

AC代码

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

int a[1005] = {0};
int n;

struct Tmp {
    int value;
    int cnt;

    bool operator<(const Tmp &t) const {
        if (this->cnt != t.cnt)
            return this->cnt < t.cnt;
        return this->value > t.value;
    }
} result[1005];

int main() {
    cin >> n;

    for (int i = 0; i < n; i++) {
        int idx;
        cin >> idx;
        a[idx]++;
    }

    int curIdx = 0;
    for (int i = 0; i <= 1000; i++) {
        if (a[i] != 0) {
            result[curIdx].value = i;
            result[curIdx].cnt = a[i];
            curIdx++;
        }
    }

    sort(result, result + curIdx);

    for (int i = curIdx - 1; i >= 0; --i) {
        cout << result[i].value << " " << result[i].cnt << endl;
    }

    return 0;
}
相关推荐
杰克尼22 分钟前
120. 三角形最小路径和
算法
树在风中摇曳28 分钟前
C语言动态内存管理:从基础到进阶的完整解析
c语言·开发语言·算法
mjhcsp41 分钟前
C++ 高精度计算:突破数据类型限制的实现与应用
开发语言·c++·算法·高精度
lixinnnn.43 分钟前
C++: map和set
开发语言·c++
大袁同学1 小时前
【二叉搜索树】:程序的“决策树”,排序数据的基石
数据结构·c++·算法·决策树·stl
郝学胜-神的一滴1 小时前
Qt QPushButton 样式完全指南:从基础到高级实现
linux·开发语言·c++·qt·程序人生
⠀One0ne1 小时前
【C++ 面试题】内存对齐
c++
蓝色汪洋1 小时前
xtu oj环--唉
算法
Algo-hx1 小时前
数据结构入门 (十):“左小右大”的秩序 —— 深入二叉搜索树
数据结构·算法
Elias不吃糖1 小时前
NebulaChat 框架学习笔记:原子变量与左值引用的工程应用
c++·学习