题目链接:https://pintia.cn/problem-sets/15/problems/867
7-40 奥运排行榜 (25 分)
每年奥运会各大媒体都会公布一个排行榜,但是细心的读者发现,不同国家的排行榜略有不同。比如中国金牌总数列第一的时候,中国媒体就公布“金牌榜”;而美国的奖牌总数第一,于是美国媒体就公布“奖牌榜”。如果人口少的国家公布一个“国民人均奖牌榜”,说不定非洲的国家会成为榜魁…… 现在就请你写一个程序,对每个前来咨询的国家按照对其最有利的方式计算它的排名。
输入格式:
输入的第一行给出两个正整数N和M(≤224,因为世界上共有224个国家和地区),分别是参与排名的国家和地区的总个数、以及前来咨询的国家的个数。为简单起见,我们把国家从0 ~ N−1编号。之后有N行输入,第i行给出编号为i−1的国家的金牌数、奖牌数、国民人口数(单位为百万),数字均为[0,1000]区间内的整数,用空格分隔。最后面一行给出M个前来咨询的国家的编号,用空格分隔。
输出格式:
在一行里顺序输出前来咨询的国家的排名:计算方式编号
。其排名按照对该国家最有利的方式计算;计算方式编号为:金牌榜=1,奖牌榜=2,国民人均金牌榜=3,国民人均奖牌榜=4。输出间以空格分隔,输出结尾不能有多余空格。
若某国在不同排名方式下有相同名次,则输出编号最小的计算方式。
输入样例:
4 4
51 100 1000
36 110 300
6 14 32
5 18 40
0 1 2 3
输出样例:
1:1 1:2 1:3 1:4
#include <iostream>
#include <queue>
#include <algorithm>
struct Country {
int goldMedals;
int medals;
int population;
int standingList[4];
};
using namespace std;
template<typename CMP>
void ranking(vector<Country*>& c, const int& pos, CMP cmp) {
if (c.empty()) return;
sort(c.begin(), c.end(), cmp); //根据lambda排序
int rank = 1;
c[0]->standingList[pos] = rank;
for (int i = 1; i < c.size(); i++) { //计算排名,注意可能出现同排名
if (cmp(c[i - 1], c[i])) //使用lambda比较
rank = i + 1;
c[i]->standingList[pos] = rank;
}
return;
}
int main() {
int n, m, t;
cin >> n >> m;
vector<Country> countrys(n);
vector<Country*> id(n); //对指针数组排序,不会打乱原数组中数据的顺序,这样就不会打乱国家的编号
for (int i = 0; i < n; i++) {
cin >> countrys[i].goldMedals >> countrys[i].medals >> countrys[i].population;
id[i] = &countrys[i];
}
ranking(id, 0,
[](Country*& a, Country*& b) {
return a->goldMedals > b->goldMedals;
});
ranking(id, 1,
[](Country*& a, Country*& b) {
return a->medals > b->medals;
});
ranking(id, 2,
[](Country*& a, Country*& b) {
return a->goldMedals / (double)a->population > b->goldMedals / (double)b->population;
});
ranking(id, 3,
[](Country*& a, Country*& b) {
return a->medals / (double)a->population > b->medals / (double)b->population;
});
for (int i = 0; i < m; i++) {
cin >> t;
int minIndex = 0;
for (int j = 1; j < 4; j++) //找出排名最高的排名方式
if (countrys[t].standingList[j] < countrys[t].standingList[minIndex])
minIndex = j;
cout << (i ? " " : "") << countrys[t].standingList[minIndex] << ":" << minIndex + 1;
}
return 0;
}