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;
}
相关推荐
CoovallyAIHub23 分钟前
Pipecat:构建实时语音 AI Agent 的开源编排框架,500ms 级端到端延迟
深度学习·算法·计算机视觉
灰色小旋风27 分钟前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
2301_8101609531 分钟前
C++与物联网开发
开发语言·c++·算法
cm65432035 分钟前
基于C++的操作系统开发
开发语言·c++·算法
ArturiaZ38 分钟前
【day57】
开发语言·c++·算法
CoovallyAIHub39 分钟前
Energies | 8版YOLO对8版Transformer实测光伏缺陷检测,RF-DETR-Small综合胜出
深度学习·算法·计算机视觉
Emberone1 小时前
排序:万物皆有序
算法·排序算法
其实秋天的枫1 小时前
2025年12月英语六级真题及答案解析完整版(第一、二、三套全PDF)
经验分享·算法
2401_874732531 小时前
C++并发编程中的死锁避免
开发语言·c++·算法
2301_792308251 小时前
C++编译期数学计算
开发语言·c++·算法