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;
}
相关推荐
m0_708830963 分钟前
C++中的享元模式实战
开发语言·c++·算法
naruto_lnq10 分钟前
分布式计算C++库
开发语言·c++·算法
m0_7066532334 分钟前
模板编译期排序算法
开发语言·c++·算法
历程里程碑35 分钟前
Linxu14 进程一
linux·c语言·开发语言·数据结构·c++·笔记·算法
木井巳39 分钟前
【递归算法】验证二叉搜索树
java·算法·leetcode·深度优先·剪枝
m0_5613596743 分钟前
嵌入式C++加密库
开发语言·c++·算法
近津薪荼43 分钟前
优选算法——双指针专题7(单调性)
c++·学习·算法
JiL 奥1 小时前
Nexus制品归档(c/c++项目)
c语言·c++
j445566111 小时前
C++中的职责链模式实战
开发语言·c++·算法
m0_686041611 小时前
实时数据流处理
开发语言·c++·算法