PAT甲级1141PAT Ranking of Institutions

时间:2020-08-11 15:51:36   收藏:0   阅读:68

题目链接

https://pintia.cn/problem-sets/994805342720868352/problems/994805344222429184

题解

题目要求

n个考生,每个考生信息为:

请输出:

思路

代码

// Problem: PAT Advanced 1141
// URL: https://pintia.cn/problem-sets/994805342720868352/problems/994805344222429184
// Tags: map unordered_map sort

#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;

struct School{
    string code;  // 小写的学校码
    double testeeScoreSums[3] = {0, 0, 0};
    int TWS;
    int Ns = 0;
    
    void calcTWS(){
        this->TWS = testeeScoreSums[0] / 1.5 + testeeScoreSums[1] + testeeScoreSums[2] * 1.5;
    }
};

// 按照要求比较两个学校
// 根据TWS非升序排序。如果TWS相等,则按Ns增序输出;如果Ns也相等,则按学校码的字母表顺序输出
bool schoolCmp(School &s1, School &s2){
    if (s1.TWS == s2.TWS)
        if (s1.Ns == s2.Ns)
            return s1.code < s2.code;
        else
            return s1.Ns < s2.Ns;
    else
        return s1.TWS > s2.TWS;
}

int main()
{
    int n, score; // the number of testees, the score of a testee
    string id, schoolCode, testLevels="BAT"; // the id of a testee, the school of a testee, three test levels
    unordered_map<string, School> schoolsMap;  // 键为学校码,值为学校

    // 获取输入
    cin >> n;
    for (int i = 0; i < n; i++){
        cin >> id >> score >> schoolCode;
        transform(schoolCode.begin(), schoolCode.end(), schoolCode.begin(), ::tolower);  // 将学校码转为小写
        schoolsMap[schoolCode].code = schoolCode;
        for (int j = 0; j < 3; j++)
            if(id[0] == testLevels[j]){
                schoolsMap[schoolCode].testeeScoreSums[j] += score; // 分别统计该校三个等级考生的总分
                schoolsMap[schoolCode].Ns += 1;  // 统计该校考生数
                break;
            }
    }

    // 将学校存入vector并排序
    vector<School> schools;
    for (unordered_map<string, School>::iterator it = schoolsMap.begin(); it != schoolsMap.end(); it++){
        it->second.calcTWS();
        schools.push_back(it->second);
    }
    sort(schools.begin(), schools.end(), schoolCmp);

    // 输出结果,如果TWS相等,则两校的rank也相等,其它输出顺序要求已通过schoolCmp控制
    int schoolNum = schools.size(), rank = 1;
    printf("%d\n%d %s %d %d\n", schoolNum, rank, schools[0].code.c_str(), schools[0].TWS, schools[0].Ns);
    for (int i = 1; i < schoolNum; i++){
        if(schools[i].TWS < schools[i-1].TWS)
            rank = i+1;
        printf("%d %s %d %d\n", rank, schools[i].code.c_str(), schools[i].TWS, schools[i].Ns);
    }
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!