CCF-CSP 201503-2 numerical sorting

Problem description
  Given n integers, please count the number of occurrences of each integer, and output in the order of the number of occurrences.
Input format
  The first line of input contains an integer n, which represents the number of given numbers.
  The second line contains n integers, and adjacent integers are separated by a space to indicate the given integer.
Output format
  output multiple lines, each line contains two integers, respectively representing a given integer and the number of times it appears. Output in descending order of occurrence. If the two integers appear as many times as possible, the smaller value is output first, and then the larger value is output.
Sample input
12
5 2 3 3 1 3 4 2 5 2 3 5
Sample output
3 4
2 3
5 3
1 1
4 1
Evaluation use case scale and convention
  1 ≤ n ≤ 1000, the given numbers are not more than 1000 Non-negative integer.

Summary of experience:
Define an unordered_map, used to store each number and the number of occurrences of this number.
Define a structure to store each number and the number of occurrences of this number.
Put the data in unordered_map into the structure and then into the vector,
then sort and output.

C ++ code:

#include<bits/stdc++.h>
using namespace std;
struct node{
	int num;
	int cnt;
	node(int num,int cnt):num(num),cnt(cnt){}
};
bool cmp(node a,node b){
	if(a.cnt == b.cnt) return a.num<b.num;
	return a.cnt>b.cnt;
}
int main() {
	int n;
	unordered_map<int,int> um;
	vector<node> v;
	scanf("%d",&n);
	while(n--){
		int num;
		scanf("%d",&num);
		um[num]++;
	}
	for(auto m:um){
		v.push_back(node(m.first,m.second));
	}
	sort(v.begin(),v.end(),cmp);
	for(auto i:v){
		printf("%d %d\n",i.num,i.cnt);
	}
	return 0;
}
Published 111 original articles · won praise 2 · Views 3533

Guess you like

Origin blog.csdn.net/m0_38088647/article/details/100633696