1036 Boys vs Girls (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.
Input Specification:
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.
Output Specification:
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.
Sample Input 1:
3
Joe M Math990112 89
Mike M CS991301 100
Mary F EE990830 95
Sample Output 1:
Mary EE990830
Joe Math990112
6
Sample Input 2:
1
Jean M AA980920 60
Sample Output 2:
Absent
Jean AA980920
NA
思路分析
定义结构体数组来存储学生的信息,属性有四个:名字、性别、ID、成绩
核心操作是 时间复杂度为O(N)的一次循环比大小
注意多设置几个男女标志位来记录需要输出的格式的相关信息
#include<cstdio>
#include<iostream>
#define MAX 1000
typedef struct{
char name[20];
char gender;
char id[20];
int grade;
}student;
student stu[MAX];
int main()
{
//input part
int N;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%s %c %s %d",stu[i].name,&stu[i].gender,stu[i].id,&stu[i].grade);
}
//calculate part
int minMaleGrade=0;int maleNum=0;int maleKey=0;
int maxFemaleGrade=0;int femaleNum=0;int femaleKey=0;
for(int i=0;i<N;i++)
{
//Male
if(stu[i].gender=='M'&&maleNum==0)
{
minMaleGrade=stu[i].grade;
maleNum++;
maleKey=i;
}
else if(stu[i].gender=='M'&&stu[i].grade<minMaleGrade)
{
minMaleGrade=stu[i].grade;
maleKey=i;
}
//Female
if(stu[i].gender=='F'&&femaleNum==0)
{
maxFemaleGrade=stu[i].grade;
femaleNum++;
femaleKey=i;
}
else if(stu[i].gender=='F'&&stu[i].grade>maxFemaleGrade)//复制上面的时候注意改全、改正确
{
maxFemaleGrade=stu[i].grade;
femaleKey=i;
}
}
//output part
if(femaleNum == 0)printf("Absent\n");
else printf("%s %s\n",stu[femaleKey].name,stu[femaleKey].id);
if(maleNum == 0)printf("Absent\n");
else printf("%s %s\n",stu[maleKey].name,stu[maleKey].id);
if(femaleNum==0||maleNum==0)printf("NA\n");
else printf("%d",stu[femaleKey].grade-stu[maleKey].grade);
}