ccf 201503-2数字排序(map排序)

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

第一种(两种差别仅在比较的函数)

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
//#define DEBUG
using namespace std;
typedef pair<int,int> PAIR;

ostream& operator<<(ostream& out,const PAIR& p ){
	return out<<p.first<<" "<<p.second;
}

bool compare(PAIR a,PAIR b){
	if(a.second != b.second) return a.second > b.second;
	else return a.first < b.first;
}

int main(){
	int n,m;
	map<int,int>q;
	cin>>n; 
	for(int i = 0;i < n; i++){
		cin>>m;
		q[m] += 1;
	}
#ifdef DEBUG
	for(map<int,int>::iterator it = q.begin();it != q.end(); ++it)
		cout<<*it<<endl;
#endif
	//将map中元素转移到vector中 
	vector<PAIR>p(q.begin(),q.end());
	sort(p.begin(),p.end(),compare);
	for(vector<PAIR>::iterator it = p.begin(); it != p.end(); ++it)
		cout<<*it<<endl; 
	return 0;
}

第二种方法

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
//#define DEBUG
using namespace std;
typedef pair<int,int> PAIR;

ostream& operator<<(ostream& out,const PAIR& p ){
	return out<<p.first<<" "<<p.second;
}

bool compare(PAIR a,PAIR b){
	if(a.second != b.second) return a.second > b.second;
	else return a.first < b.first;
}

struct compare{
	bool operator()(const PAIR& lhs,const PAIR& rhs){
		if(lhs.second != rhs.second) return lhs.second > rhs.second;
		else return lhs.first < rhs.first;
	}
};


int main(){
	int n,m;
	map<int,int>q;
	cin>>n; 
	for(int i = 0;i < n; i++){
		cin>>m;
		q[m] += 1;
	}
#ifdef DEBUG
	for(map<int,int>::iterator it = q.begin();it != q.end(); ++it)
		cout<<*it<<endl;
#endif
	//将map中元素转移到vector中 
	vector<PAIR>p(q.begin(),q.end());
	sort(p.begin(),p.end(),compare());
	for(vector<PAIR>::iterator it = p.begin(); it != p.end(); ++it)
		cout<<*it<<endl; 
	return 0;
}

map排序理解阅读
map排序详尽

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值