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;
}
相关推荐
谎言西西里2 小时前
LeetCode 热题100 --- 双指针专区
算法
qq_466302454 小时前
vs2008 Hotlink实时数据读取
c++·qt
阿达King哥5 小时前
关于C++中的typedef typename的含义
c++
leo__5205 小时前
基于两步成像算法的聚束模式SAR MATLAB实现
开发语言·算法·matlab
前端小白在前进5 小时前
力扣刷题:在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
咔咔咔的6 小时前
3652. 按策略买卖股票的最佳时机
c++
某林2126 小时前
基于SLAM Toolbox的移动机器人激光建图算法原理与工程实现
stm32·嵌入式硬件·算法·slam
修炼地7 小时前
代码随想录算法训练营第四十三天 | 图论理论基础、深搜理论基础、卡码网98. 所有可达路径、797. 所有可能的路径、广搜理论基础
算法·深度优先·图论
iAkuya7 小时前
(leetcode)力扣100 23反转链表(迭代||递归)
算法·leetcode·链表
剪一朵云爱着7 小时前
PAT 1095 Cars on Campus
算法·pat考试