[A PAT every day] 1012 The Best Rank

Ideas

This question examines the sorting of structures.
Practice the use of sort in algorithm
1. Use the structure to store the scores of each subject in each student, and rank in each subject
. 2. Use sort to enter the rank of each subject. Note here! There may be a situation of 1223, remember to skip
3. Compare the ranking of each student to find the optimal ranking
4. Output

#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;
}

Guess you like

Origin www.cnblogs.com/xinyuLee404/p/12682170.html