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;
}
相关推荐
不吃洋葱.6 分钟前
有序数组的平方
数据结构·算法·leetcode
小破农16 分钟前
手撕 STL 之—— list
开发语言·c++
程序员老茶16 分钟前
C++:STL的常用容器(string/vector/deque/stack/queue/list/set/multiset/map/multimap)
开发语言·c++·list
拾忆-eleven25 分钟前
C++ 算法(2):STL list 完全解析,从入门到高效使用
开发语言·c++·算法
uhakadotcom26 分钟前
介绍TxGemma:提升药物研发效率的AI模型
算法·面试·github
筱戥芊茹32 分钟前
RK3588上Linux系统编译C/C++ Demo时出现BUG:The C/CXX compiler identification is unknown
linux·c语言·c++·嵌入式硬件·bug
abant21 小时前
leetcode 3504 回文+最长公共子数组
算法·leetcode·职场和发展
黑不溜秋的1 小时前
C++ 编程指南36 - 使用Pimpl模式实现稳定的ABI接口
开发语言·c++
JCBP_1 小时前
I/O进程5
服务器·c语言·后端·算法
森焱森1 小时前
单片机领域中哈希表
c语言·人工智能·单片机·嵌入式硬件·算法