【每天一道PAT】1012 The Best Rank

思路

本题考查结构体排序
练习使用algorithm中的sort用法
1.使用结构体存储每个学生的各科成绩,各科排名
2.使用sort录入各科排名,这里注意!有可能出现1223的情况,记得跳过
3.对每个学生的排名进行比较找到最优排名
4.输出结果

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int M,N;//记录录入总人数以及查找总人数
char course[5] = {'C', 'M', 'E', 'A'};//存储各个科目名称
struct node{
    int id;
    int score[4];
    int rank[4];
    int bestrank;
    int bestcourse;
}stu[2005];
int f = 0;//更新f对每个科目进行排名
bool cmp1(node a, node b)
{
    return a.score[f]>b.score[f];
}
void read_rank()
{
    for (int i = 0; i < M; ++i)
    {
        cin>>stu[i].id >>stu[i].score[0] >>stu[i].score[1] >>stu[i].score[2];
        stu[i].score[3] = (stu[i].score[0]+stu[i].score[1]+stu[i].score[2])/3.0;
    }
    for (f = 0; f <=3; ++f) {
        sort(stu,stu + M,cmp1);
        stu[0].rank[f] = 1;
        //此处注意当成绩相同时,排名相同且排名跳过
        int index = 1;
        for (int j = 1; j < M; ++j)
        {
            if(stu[j].score[f]!=stu[j-1].score[f])
            {
                index++;
                stu[j].rank[f]=index;
            }
            else
            {
                stu[j].rank[f]=index;
                index++;
            }
        }
    }
}
int main()
{
    int search_id;
    scanf("%d %d",&M,&N);
    read_rank();
    for (int i = 0; i < M; ++i)
    {
        int flag = 3;
        int min = stu[i].rank[3];//由于A的优先权最大,先将最小记录为A
        for (int j = 0; j < 3; ++j)
        {
            if(stu[i].rank[j] < min)
            {
                min = stu[i].rank[j];//更新最小值
                flag = j;//找到最小值对应科目
            }
        }
        stu[i].bestcourse = flag;
        stu[i].bestrank = stu[i].rank[flag];
    }
    for (int j = 0; j < N; ++j)
    {
        int k;
        scanf("%d",&search_id);
        for (k = 0; k < M; ++k)
        {
            if(search_id == stu[k].id) break;//查找学生id
        }
        if(k == M) printf("N/A\n");
        else
            printf("%d %c\n",stu[k].bestrank,course[stu[k].bestcourse]);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xinyuLee404/p/12682170.html
今日推荐