zoukankan      html  css  js  c++  java
  • CCF CSP 201503-2 数字排序

    CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址

    CCF CSP 201503-2 数字排序

    问题描述

      给定n个整数,请统计出每个整数出现的次数,按出现次数从多到少的顺序输出。

    输入格式

      输入的第一行包含一个整数n,表示给定数字的个数。
      第二行包含n个整数,相邻的整数之间用一个空格分隔,表示所给定的整数。

    输出格式

      输出多行,每行包含两个整数,分别表示一个给定的整数和它出现的次数。按出现次数递减的顺序输出。如果两个整数出现的次数一样多,则先输出值较小的,然后输出值较大的。

    样例输入

    12
    5 2 3 3 1 3 4 2 5 2 3 5

    样例输出

    3 4
    2 3
    5 3
    1 1
    4 1

    评测用例规模与约定

      1 ≤ n ≤ 1000,给出的数都是不超过1000的非负整数。

    解析

    使用map数据结构计数。

    然后把计数的结果用Node对象表示,存到vector里,同时重载operator<来自定义排序规则。

    代码

    C++

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <map>
    using namespace std;
    
    struct Node {
        int num;
        int cnt;
        Node(int n, int c) : num(n), cnt(c) {}
        bool operator<(const Node & other) const {
            if(cnt > other.cnt) return true;
            else if(cnt == other.cnt && num < other.num) return true;
            return false;
        }
    };
    
    int main() {
        int N;
        cin >> N;
        map<int,int> counter;
        for(int i=0; i<N; i++) {
            int num;
            cin >> num;
            counter[num]++;
        }
        vector<Node> vec;
        for(map<int,int>::iterator it=counter.begin(); it!=counter.end(); it++) {
            vec.push_back(Node(it->first, it->second));
        }
        sort(vec.begin(), vec.end());
        for(int i=0; i<vec.size(); i++) {
            cout << vec[i].num << " " << vec[i].cnt << endl;
        }
    }
  • 相关阅读:
    web前端优化之reflow(减少页面的回流)
    Javascript深拷贝
    MySQL 配置优化
    MySQ中Lmax_connections的合理设置
    Too many connections解决方案
    Linux 查看文件内容
    ON DUPLICATE KEY UPDATE
    jquery $.each 和for怎么跳出循环终止本次循环
    使用redis避免客户端频繁提交数据
    windows下为mysql添加日志
  • 原文地址:https://www.cnblogs.com/meelo/p/7677859.html
Copyright © 2011-2022 走看看