【PAT A1036】Boys VS Girls(25分)

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805453203030016
题目分值:25分
题目类型:排序

题目描述

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 grade​F−gradeM.If one such kind of student is missing, output Absent in the corresponding line, and output NA in the third line instead.

输入样例1

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

输出样例1

Mary EE990830
Joe Math990112
6

输入样例2

1
Jean M AA980920 60

输出样例2

Absent
Jean AA980920
NA

思路分析

  • 题目大意:
  • 1.按照一定的格式录入学生的成绩
  • 2.取男生最低分,取女生最高分并输出,如果没有,则输出Absent
  • 3.最后输出女生最高分减去男生最低分的差值,如果第二步中有不存在的,则不存在差值,输出NA
  • 操作方法:
  • 1.男女分别用两个结构体数组存储,然后sort排序
  • 2.设置flag,男女只要缺一个,直接false,第三步就可以判定了

注意点

  • 结构体可以赋值,所以一边读取成绩一遍存储,直接用temp赋值给男女即可
  • 最后是女生成绩减去男生成绩,不要粗心

参考代码

C/C++

#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 10010;
struct stu1036
{
    char name[11];
    char id[11];
    int grade;
}stu_m[maxn],stu_f[maxn];    //男女要分开排序 

bool cmp(stu1036 a,stu1036 b)
{
    return a.grade > b.grade;
}

int main()
{
    int n,cnt_m = 0,cnt_f = 0;    //存储男女人数 
    scanf("%d",&n);
    while(n--)
    {
        stu1036 temp;
        char gender;
        scanf("%s %c %s %d",temp.name,&gender,temp.id,&temp.grade);
        if(gender == 'M')    //信息是男
            stu_m[cnt_m++] = temp;
        else
            stu_f[cnt_f++] = temp; 
    }
    
    bool flag = true;    //计算第三个输出,如果前两个条件任一不满足,就输出NA
    if(cnt_f)    //打印女生成绩 
    {
        sort(stu_f,stu_f + cnt_f,cmp);
        printf("%s %s\n",stu_f[0].name,stu_f[0].id);
    }
    else
    {
        flag = false;
        printf("Absent\n");
    }
    if(cnt_m)    //打印男生成绩 
    {
        sort(stu_m,stu_m + cnt_m,cmp);
        printf("%s %s\n",stu_m[cnt_m-1].name,stu_m[cnt_m-1].id);
    } 
        else
    {
        flag = false;
        printf("Absent\n");
    }
    if(flag)        //前两步没有问题,输出成绩差 
        printf("%d",stu_f[0].grade - stu_m[cnt_m-1].grade);
    else
        printf("NA");
    return 0;
}
文章目录