PAT B1004. 成绩排名

题目描述:

读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。

输入格式:

每个测试输入包含 1 个测试用例,格式为:

第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
… … …
第 n+1 行:第 n 个学生的姓名 学号 成绩

其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。

输出格式:

对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。

输入样例:

3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95

输出样例:

Mike CS991301
Joe Math990112

思路:

步骤一: 用结构体student记录单个学生的姓名、学号、分数,并定义sort的比较函数cmp,使得排序时按照student分数从大到小的顺序进行排列;
步骤二: 主函数中先输入学生个数n,定义有n个student的结构体数组stus[n],紧接着输入n个学生的信息,并将这n个学生的信息存放到stus[n]中;
步骤三:sort函数对stus[n]里的学生进行排序(按照分数从大到小排),并输出第1个学生stus[0](分数最高)和第n个学生stus[n-1](分数最低)的信息。

代码

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

struct student
{
    string name, id;
    int score;
};

bool cmp(student a, student b)
{
    return a.score > b.score;
}

int main()
{
    int n, s;
    cin>>n;
    student stus[n];
    for(int i = 0; i < n; i++)
    {
        cin>>stus[i].name>>stus[i].id>>stus[i].score;
    }
    sort(stus, stus+n, cmp);
    cout<<stus[0].name<<" "<<stus[0].id<<endl;
    cout<<stus[n-1].name<<" "<<stus[n-1].id<<endl;
    return 0;
}

提交结果

在这里插入图片描述

发布了7 篇原创文章 · 获赞 7 · 访问量 340

猜你喜欢

转载自blog.csdn.net/qq_42554780/article/details/104221517