PAT甲级1141 PAT Ranking of Institutions (25分)|C++实现

一、题目描述

原题链接
After each PAT, the PAT Center will announce the ranking of institutions based on their students’ performances. Now you are asked to generate the ranklist.

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input:

10
A57908 85 Au
B57908 54 LanX
A37487 60 au
T28374 67 CMU
T32486 24 hypu
A66734 92 cmu
B76378 71 AU
A47780 45 lanx
A72809 100 pku
A03274 45 hypu

Sample Output:

5
1 cmu 192 2
1 au 192 3
3 pku 100 1
4 hypu 81 2
4 lanx 81 2

二、解题思路

结构体排序题,因为我们最后要对学校进行排序,所以可以把学校设置成一个结构体,包括它的名称、所有学生的总分,以及排名。随后,我们用一个unordered_map<string, School>建立一个从字符串到该结构体School的映射,每输入一个数据就更新对应学校的总分,之后遍历这个map更新每个学校的排名,最后输出即可。详情见代码注释。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
struct Student
{
  string id, school;
  int score;
};
struct School   
{
  string name;
  double total = 0; //计算总分
  int rounded, cnt=0, rank; //总分(四舍五入后),参加人数,排名
};
unordered_map<string, School> mp;
vector<School> ans;
string to_lower(string str) //大写转小写
{
  string ans = str;
  for(int i=0; i<ans.size(); i++)
  {
    if(ans[i]>='A' && ans[i]<='Z')	ans[i] = 'a' - 'A' + ans[i];
  }
  return ans;
}
bool cmp(School a, School b)
{
  if(a.rounded != b.rounded)	return a.rounded > b.rounded;   //先按分数
  else if(a.cnt != b.cnt)	return a.cnt < b.cnt;   //分数相同则按总人数从小到大
  else	return a.name.compare(b.name) < 0;  //最后按名称排序
}
int main()
{
  int N;
  scanf("%d", &N);
  Student tmp;
  for(int i=0; i<N; i++)
  {
    cin >> tmp.id >> tmp.score >> tmp.school;
    if(tmp.id[0] == 'A')	mp[to_lower(tmp.school)].total += tmp.score;    //把输入的分数加入该学校的总分数中
    else if(tmp.id[0] == 'B')	mp[to_lower(tmp.school)].total += tmp.score/1.5;
    else	mp[to_lower(tmp.school)].total += tmp.score*1.5;
    mp[to_lower(tmp.school)].cnt++;
  }
  for(auto it : mp) //遍历map,更新总分四舍五入后的分数
  {
    it.second.name = it.first;
    it.second.rounded = (int)it.second.total;
    ans.push_back(it.second);   //存入结果vector
  }
  sort(ans.begin(), ans.end(), cmp);
  printf("%d\n", ans.size());
  for(int i=0; i<ans.size(); i++)
  {
    if(i==0)	ans[i].rank = 1;
    else
    {
      if(ans[i].rounded == ans[i-1].rounded)	ans[i].rank = ans[i-1].rank;
      else	ans[i].rank = i+1;
    }
    printf("%d %s %d %d\n", ans[i].rank, ans[i].name.c_str(), ans[i].rounded, ans[i].cnt);
  }
  return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值