【PAT1141】PAT Ranking of Institutions

1.题目

请添加图片描述
请添加图片描述
请添加图片描述

2.代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <unordered_map>
using namespace std;
const int N = 100010;
struct School{
    string name;
    double score;
    int count;
    
    School(): count(0), score(0) {}
    
    bool operator< (const School &t) const{
        if(score != t.score) return score>t.score;
        if(count != t.count) return count < t.count;
        return name<t.name;
    }
};
int main(){
    int n;
    cin>>n;
    unordered_map<string, School> hash;
    //读进输入,构建哈希表
    for(int i=0; i<n; i++){
        double grade;
        string id;
        string schName;
        cin>>id>>grade>>schName;
        //将学校转化为小写
        for(auto& c: schName) c = tolower(c);
        
        if(id[0] == 'B'){
            //如果是乙级,除以1.5,并注意精度的设置
            grade = grade / 1.5;
        }else if(id[0] == 'T'){
             //如果是顶级,则乘1.5
             grade = grade * 1.5;
        }
        hash[schName].name = schName;
        hash[schName].score += grade;
        hash[schName].count++;
    }
    //将hash表里的内容放入vector中,并对vector进行排序
    vector<School> schools;
    for(auto item:hash){
        //将hash表里的内容放入vector中
        item.second.score = (int)(item.second.score+1e-8);
        schools.push_back(item.second);
    }
    //对vector进行排序
    sort(schools.begin(), schools.end());
    int length = schools.size();
    cout<<length<<endl;
    int rank = 1;
    for(int i=0; i<length; i++){
        auto s = schools[i];
        if(i && s.score != schools[i-1].score){
            rank = i+1;
        }
        printf("%d %s %d %d\n", rank, s.name.c_str(), (int)s.score, s.count);
    }
    
    
    
    return 0;
}

3.解题思路

该题的解决方法分为两步:

  1. 创造一个哈希表,key是学校名(小写、string),value是结构体School(学校名、学校对应的总分、学校对应的考生人数)组成。并在读入输入的过程中将该哈希表构建起来。
  2. 将哈希表中的内容放到一个类型是结构体School的vector中,再利用sort函数对该学校的成绩进行排序,排序的原则在结构体的<符号函数中进行定义。
  3. 输出排序的内容,并赋予其rank。

4.注意点

  1. 关于把字符串变成小写形式的代码:
for(auto& c: schName) c = tolower(c);
  1. 关于排序函数的内在原则定义:
bool operator< (const School &t) const{
        if(score != t.score) return score>t.score;
        if(count != t.count) return count < t.count;
        return name<t.name;
    }
  1. 关于结构体内部的初始函数的定义函数:
School(): count(0), score(0) {}
  1. 关于精度的控制代码:
item.second.score = (int)(item.second.score+1e-8);
  1. 关于rank的定义:
int rank = 1;
    for(int i=0; i<length; i++){
        auto s = schools[i];
        if(i && s.score != schools[i-1].score){
            rank = i+1;
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值