PAT(Advanced Level)A1141. PAT Ranking of Institutions

题意

按照对应要求输出排序后的结果

思路

  • 按照题目的要求拆解整合信息,并且按照要求排序和输出就好了
  • unordered_map<>内部不会自己排序,更快
  • 这里要是用cin, cout会超时
  • 排名处理
    • 设置2个变量,一个是当前应该对应的排名rank,一个是人数men
    • 每一次我们检查和上一个人的分数看是否相等来更新名次

代码

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
struct node {
    string id;
    int scoreB, scoreA, scoreT;
    int total_weight;
    int cnt;
};

void tolower(string& s) {
    for(auto &ch: s) {
        if(isupper(ch)) {
            ch = (ch - 'A') + 'a';
        }
    }
}

int main() {
    int n, tmp;
    scanf("%d", &n);
    string id_tmp, school_tmp;
    unordered_map<string, node> mp;
    unordered_map<string, int> school_cnt;
    
    for(int i = 0; i < n; i++) {
        cin >> id_tmp;
        scanf("%d", &tmp);
        cin >> school_tmp;
        tolower(school_tmp);
        school_cnt[school_tmp]++;
        switch(id_tmp[0]) {
            case('A') : {mp[school_tmp].scoreA += tmp; break;}
            case('B') : {mp[school_tmp].scoreB += tmp; break;}
            case('T') : {mp[school_tmp].scoreT += tmp; break;}
        }
    }
    
    vector<node> v;
    for(auto &it: mp) {
        double t = it.second.scoreB / 1.5 + it.second.scoreA + it.second.scoreT * 1.5;
        it.second.total_weight = (int)t;
        it.second.cnt = school_cnt[it.first];
        it.second.id = it.first;
        v.emplace_back(it.second);
    }
    
    sort(v.begin(), v.end(), [&](node x, node y) {
        if(x.total_weight == y.total_weight) {
            if(x.cnt == y.cnt) {
                return x.id < y.id;
            }else {
                return x.cnt < y.cnt;
            }
        }
        return x.total_weight > y.total_weight;
    });
    
    cout << v.size() << endl;
    if(v.size() != 0) {
        int rank = 1, men = 1;
        printf("1 %s %d %d\n", v[0].id.c_str(), v[0].total_weight, v[0].cnt);
        for(int i = 1; i < v.size(); i++) {
            men++;
            if(v[i].total_weight != v[i - 1].total_weight)  rank = men;
            printf("%d %s %d %d\n", rank, v[i].id.c_str(), v[i].total_weight, v[i].cnt);
        }
    }
    return 0;
}
上一篇:A-1025 PAT Ranking (25 分)


下一篇:Android Gradle的使用