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;
}
相关推荐
闪电麦坤954 分钟前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
C++、Java和Python的菜鸟32 分钟前
第六章 统计初步
算法·机器学习·概率论
Cx330❀33 分钟前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
散11242 分钟前
01数据结构-Prim算法
数据结构·算法·图论
起个昵称吧1 小时前
线程相关编程、线程间通信、互斥锁
linux·算法
阿巴~阿巴~1 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
..过云雨2 小时前
01.【数据结构-C语言】数据结构概念&算法效率(时间复杂度和空间复杂度)
c语言·数据结构·笔记·学习
myzzb2 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa
拂晓银砾2 小时前
Java数据结构-栈
java·数据结构
旺小仔.2 小时前
双指针和codetop复习
数据结构·c++·算法