1141 PAT Ranking of Institutions 之 STL map排序

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 分析

题意:题目将给出若干条考生信息,以以下形式给出:id,分数,学校名;现在要你按照学院进行排序,每个学院的总分有考生的成绩组成:ScoreB/1.5 + ScoreA + ScoreT*1.5,最后按照总分进行排名,若分数相同则学院人数少的在前,若人数还相等,则按学院名称降序排列。同时输出每个学院的人数和排名。

3. 解题过程

  1. 这是一道十分常见的排序题,因为题目最后要求输出学院对应的总分和人数,所以考虑建立一个以学院名称为键,对应值为value的map进行解题。
  2. 可见,需要建立一个结构体来储存每个学院的总分、人数和名字。
  3. 然后关于排序优先根据题意新建一个cmp利用sort完成。
  4. 可能这道有一点需要注意的是,每个学院的成绩是所有分数加起来后才取整,如果按每个先计算再加起来最后一个测试点会过不了。
  5. 最后关于排名的,算法是只要分数跟前一个不同就按人数排名,否则跟前一个排名一样。
  6. 请看完整代码:
#include<iostream>
#include<algorithm>
#include<cctype>
#include<vector>
#include<unordered_map>
using namespace std;
struct node
{
	string school;
	int tws, ns;
};
bool cmp(node a, node b)
{
	if(a.tws != b.tws)
	{
		return a.tws > b.tws;
	}
	else if(a.ns != b.ns)
	{
		return a.ns < b.ns;
	}
	else return a.school < b.school;
}
int main()
{
	int n; scanf("%d", &n);
	unordered_map<string, int> cnt;
	unordered_map<string, double> sum;
	for(int i = 0; i < n; i++)
	{
		string id, school;
		cin >> id;
		double score;
		scanf("%lf", &score);
		cin >> school;
		for(int j = 0; j < school.length(); j++)
		{
			school[j] = tolower(school[j]);
		}
		if(id[0] == 'B') score = score/1.5;
		else if(id[0] == 'T') score = score * 1.5;
		sum[school] += score;
		cnt[school] ++;
	}
	vector<node> ans;
	for(auto it = cnt.begin(); it != cnt.end(); it++)
	{
		ans.push_back(node{it -> first, (int) sum[it -> first], cnt[it -> first]});
	}
	sort(ans.begin(), ans.end(), cmp);
	int rank = 0, pres = -1;
	printf("%d\n", ans.size());
	for(int i = 0; i < ans.size(); i++)
	{
		if(pres != ans[i].tws) rank = i + 1;
		pres = ans[i].tws;
		printf("%d ", rank);
		cout << ans[i].school;
		printf(" %d %d\n", ans[i].tws, ans[i].ns);
	}
	return 0;
}

4. 小结

  1. 这题的总体思路是按照利用结构体储存相关信息并输出,中间利用sort和vector功能搭配使用排序,数值的赋予则是靠map中名字与数值的一一对应。可能比较难理解的是下面的代码:
for(auto it = cnt.begin(); it != cnt.end(); it++)
	{
		ans.push_back(node{it -> first, (int) sum[it -> first], cnt[it -> first]});
	}

如果不太熟练可以分开步骤进行替代:

for(auto it = cnt.begin(); it != cnt.end(); it++)
{
	node a;
	a.school = it -> first;
	a.tws = (int) sum[it -> first];
	a.ns = cnt[it -> first];
	ans.push_back(a);
}

感谢阅读,请多多支持!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值