结构与算法 7-40 奥运排行榜 (60行精简 lambda的运用)

题目链接: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;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值