1012 The Best Rank (25 point(s))

1012 The Best Rank (25 point(s))

To evaluate the performance of our first year CS majored students, we consider their grades of three courses only: C - C Programming Language, M - Mathematics (Calculus or Linear Algrbra), and E - English. At the mean time, we encourage students by emphasizing on their best ranks -- that is, among the four ranks with respect to the three courses and the average grade, we print the best rank for each student.

For example, The grades of CME and A - Average of 4 students are given as the following:

StudentID  C  M  E  A
310101     98 85 88 90
310102     70 95 88 84
310103     82 87 94 88
310104     91 91 91 91

Then the best ranks for all the students are No.1 since the 1st one has done the best in C Programming Language, while the 2nd one in Mathematics, the 3rd one in English, and the last one in average.

Example:

#include<iostream>
#include<algorithm>
#include<vector>
#include<map>

using namespace std;

struct Subject {
    int score;
    int id;
};

typedef enum {Average, CP, Math, English, Num} Sub;
char Title[] = {'A', 'C', 'M', 'E'};

void Ranking(vector<Subject> &s, vector<string> &id, 
             map<string, vector<int>> &rank, int sub)
{
    int r = 0, cnt = 0;
    int last = -1;
    sort(s.begin(), s.end(), [](Subject &a, Subject &b){return a.score > b.score;});
    for(auto x : s) {
        cnt++;
        if(last != x.score)
            r=cnt, last = x.score;
        rank[id[x.id]][sub] = r;
    }
}

int main()
{
    int n, m;
    cin >> n >> m;
    vector<Subject> SUB[Num];
    vector<string>  ID(n);
    map<string, vector<int>> rank;
    for(int i = Average; i < Num; i++) SUB[i].resize(n);
    for(int i = 0; i < n; i++) {
        SUB[Average][i].id = SUB[CP][i].id = SUB[Math][i].id = SUB[English][i].id = i;
        cin >> ID[i];
        cin >> SUB[CP][i].score >> SUB[Math][i].score >> SUB[English][i].score;
        SUB[Average][i].score = (SUB[CP][i].score + SUB[Math][i].score + SUB[English][i].score) / 3;
        rank[ID[i]].resize(Num);
    }
    for(int i = Average; i < Num; i++) Ranking(SUB[i], ID, rank, i);
    for(int i = 0; i < m; i++) {
        string id;
        cin >> id;
        if(rank.find(id) == rank.end()) 
            cout << "N/A\n";
        else {
            auto it = min_element(rank[id].begin(), rank[id].end());
            cout << *it << ' ' << Title[it-rank[id].begin()] << endl;
        }
    }
}

思路:

利用 sort 对单科进行排名,然后记录在 rank 里,然后查找时,再对各科排名进行筛选,最后得出结果。

注意排名若有重复,则下一位排名不能简单加一, 例如 1,1,3,3 而不是 1,1,2,2

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/113924287