ccf 201503-2 数字排序

问题描述
试题编号:        201503-2
试题名称: 数字排序
时间限制: 1.0s
内存限制: 256.0MB
问题描述: 问题描述
     给定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的非负整数。

c++代码如下:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

struct num{
    int val;
    int count;
    num(int a, int b):val(a), count(b){};
};
bool cmp(num a, num b){
    if(a.count != b.count){
        return a.count>b.count;
    }else{
        return a.val<b.val;
    }
}
int main(){
    int n, x;
    cin >> n;
    map<int, int>mp;
    for(int i=0; i<n; i++){
        cin >> x;
        mp[x]++;
    }
    vector<num> v;
    for(map<int, int>::iterator it = mp.begin(); it!=mp.end(); it++){
        int x = it->first;
        int y = it->second;
        num *t = new num(x,y);
        v.push_back(*t);
    }
    sort(v.begin(), v.end(), cmp);
    
    for(int i=0; i<v.size(); i++){
        cout << v[i].val << " " << v[i].count <<endl;
    }
    return 0;
}
发布了38 篇原创文章 · 获赞 37 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Lsxlsxls/article/details/105280133
今日推荐