CCF201503-2 数字排序(100分)

试题编号: 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的非负整数。

问题链接:CCF201503-2 数字排序

问题分析:简单题,使用map<int,int>第一个元素表示值,第二个元素表示出现的次数

程序说明:C++程序使用了sort排序,以及使用了有关map的简单操作。

提交后得100分的C++程序:

#include<iostream>
#include<algorithm>
#include<map>

using namespace std;

const int N=1000;

struct Number{
	int val;//值 
	int cnt;//出现的次数 
	bool operator<(const Number &a)const
	{//按出现的次数从多到少的顺序排列,如果一样多,按值的大小从小到大排列 
		return (cnt==a.cnt)?(val<a.val):(cnt>a.cnt);
	}
}a[N];

int main()
{
	map<int,int>d;
	int n;
	cin>>n;
	while(n--){
		int x;
		cin>>x;
		d[x]++;
	}
	int m=0;
	for(map<int,int>::iterator it=d.begin();it!=d.end();it++){  //遍历
	  a[m].val=it->first;
	  a[m++].cnt=it->second; 
	}
	sort(a,a+m);
	for(int i=0;i<m;i++)
	  cout<<a[i].val<<" "<<a[i].cnt<<endl;
	return 0;
	  
 } 

猜你喜欢

转载自blog.csdn.net/songbai1997/article/details/81189952
今日推荐