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;
}
相关推荐
jyan_敬言1 小时前
【C++】string类(二)相关接口介绍及其使用
android·开发语言·c++·青少年编程·visual studio
liulilittle1 小时前
SNIProxy 轻量级匿名CDN代理架构与实现
开发语言·网络·c++·网关·架构·cdn·通信
张人玉2 小时前
C# 常量与变量
java·算法·c#
学不动CV了2 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
tan77º2 小时前
【Linux网络编程】Socket - UDP
linux·服务器·网络·c++·udp
weixin_446122462 小时前
LinkedList剖析
算法
GiraKoo2 小时前
【GiraKoo】C++14的新特性
c++
悠悠小茉莉3 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
坏柠3 小时前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
泽02023 小时前
C++之红黑树认识与实现
java·c++·rpc