PAT甲级(Advanced Level)练习题 Boys vs GirlsBoys vs Girls

题目描述

This time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students.

输入描述:

Each input file contains one test case. Each case contains a positive integer N, followed by N lines of student information. Each line contains a student’s name, gender, ID and grade, separated by a space, where name and ID are strings of no more than 10 characters with no space, gender is either F (female) or M (male), and grade is an integer between 0 and 100. It is guaranteed that all the grades are distinct.

输出描述:

For each test case, output in 3 lines. The first line gives the name and ID of the female student with the highest grade, and the second line gives that of the male student with the lowest grade. The third line gives the difference gradeF-gradeM. If one such kind of student is missing, output “Absent” in the corresponding line, and output “NA” in the third line instead.

输入例子:

3
Joe M Math990112 89
Mike M CS991301 100
Mary F EE990830 95

输出例子:

Mary EE990830
Joe Math990112
6

题目分析及实现

把所有的学生信息存在一个结构体数组中,然后按照grade属性进行排序。从前往后找到第一个女生同学即是年级最高的女生。从后往前找第一个男生即是年级最低的男生。然后把他们的属性输出出来,再计算二者的年级差,即可得到正确结果。

代码实现(C++版本)

#include <iostream>
#include <algorithm>

using namespace std;

struct Student{
    string name;
    char gender;
    string id;
    int grade;
};

bool compare(Student a,Student b){
    return a.grade > b.grade;
}

int main()
{
    int n;
    cin >> n;
    Student stu[n];
    for(int i =0; i < n;i++){
        cin >> stu[i].name >> stu[i].gender >> stu[i].id >> stu[i].grade;
    }

    sort(stu,stu+n,compare);
    //找出最高年级女生.
    Student girl;
    bool girlFind = false;
    for(int i =0;i<n;i++){
        if(stu[i].gender == 'F'){
            girl = stu[i];
            girlFind =  true;
            break;
        }
    }
    //找到最低年级男生;
    Student boy;
    bool boyFind = false;
    for(int i =n-1;i>=0;i--){
        if(stu[i].gender == 'M'){
            boy = stu[i];
            boyFind = true;
            break;
        }
    }
    if(!girlFind){
        cout<<"Absent"<<endl;
    }else{
        cout<<girl.name << " "<<girl.id<<endl;
    }
    if(!boyFind){
        cout<<"Absent"<<endl;
    }else{
        cout << boy.name<<" "<<boy.id<<endl;
    }
    if(girlFind&&boyFind){
        cout<< girl.grade - boy.grade<<endl;
    }else{
        cout<<"NA"<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37221167/article/details/88699550