标签:
该题也是一道简单题,由“评测用例规模与约定”可以得出输入规模不大,在[1,1000]之间。下面给出多种方法:
1、使用C++的sort函数进行排序
#include<iostream> #include<algorithm> using namespace std; struct num{ int val; int t; }; bool cmp(num a, num b){ if(a.t != b.t) return a.t>b.t; return a.val<b.val; } num a[1001]; int main(){ int n, i, x; for(i=0;i<=1001;++i){ a[i].val = i; } cin>>n; for(i=1;i<=n;++i){ cin>>x; ++a[x].t; } sort(a, a+n, cmp); for(i=0;i<=n;++i){ if(a[i].t==0) break; cout<<a[i].val<<‘ ‘<<a[i].t<<endl; } return 0; }
自定义实现sort函数
using namespace std; typedef struct countInt{ int number; int counts; }; //countInt A[1001]; void quickSort(countInt A[], int l, int r) { if (l < r) { int i = l; int j = r; countInt tmp = A[i]; while (i < j) { while (i < j && (A[j].counts <= tmp.counts)) { //如果不满足,跳出循环,将A[j]放到A[i]的位置上 if (A[j].counts == tmp.counts && A[j].number < tmp.number) break; j--; } if (i < j) { A[i] = A[j]; i++; } while (i < j && (A[i].counts >= tmp.counts)) { if (A[i].counts == tmp.counts && A[i].number > tmp.number) break; i++; } if (i < j) { A[j] = A[i]; j--; } } A[i] = tmp; quickSort(A, l, i - 1); quickSort(A, i + 1, r); } }
2、STL模板实现
#include <utility> #include <iostream> #include <map> #include <iterator> #include <functional> using namespace std; int main(){ map<int, int> numAndCounts; multimap<int, int, greater<int> > heapMax; int n; cin >> n; for (int i = 0; i<n; i++) { int a; cin >> a; numAndCounts[a]++; } for (map<int, int>::iterator it = numAndCounts.begin(); it != numAndCounts.end(); it++) { heapMax.insert(pair<int, int>(it->second, it->first)); } for (map<int, int>::iterator it = heapMax.begin(); it != heapMax.end(); it++) { cout << it->second << " " << it->first << endl; } return 0; }
第二种方法代码比较简单,但是必须对STL有深入的了解。其实看一下包含的头文件就知道了!
标签:
原文地址:http://www.cnblogs.com/tgycoder/p/4988478.html