问题
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 grade
F
−grade
M
. 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
结尾无空行
思路
用sort对结构体数组进行排序,分别用两个数组代表男生和女生。按分数从高到低排序。女生最高分-男生最低分,将相关信息输出。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
struct student{
string name;
char gender;
string id;
int grade;
student(){}
student(string _name,char _gender,string _id,int _grade):name(_name),gender(_gender),id(_id),grade(_grade){}
};
student stuM[maxn],stuF[maxn];
bool cmp(student a,student b){
return a.grade>b.grade;
}
int main(){
int n,grade,num_M=0,num_F=0;
string name,id;
char gender;
cin>>n;
for (int i = 0; i < n; ++i) {
cin>>name>>gender>>id>>grade;
student s = student(name,gender,id,grade);
if(gender == 'M'){
stuM[i] = s;
num_M++;
}
else if(gender=='F'){
stuF[i] = s;
num_F++;
}
}
sort(stuM,stuM+maxn,cmp);
sort(stuF,stuF+maxn,cmp);
if(num_F==0)
cout<<"Absent"<<endl;
else{
cout<<stuF[0].name<<" "<<stuF[0].id<<endl;
}
if(num_M==0)
cout<<"Absent"<<endl;
else{
cout<<stuM[num_M-1].name<<" "<<stuM[num_M-1].id<<endl;
}
if(num_M!=0 && num_F!=0){
int ans = stuF[0].grade - stuM[num_M-1].grade;
cout<<ans<<endl;
}
else{
cout<<"NA"<<endl;
}
return 0;
}
总结
1.sort函数的写法要注意last也就是第二个参数要是maxn,不能是学生数量。
2.注意输出NA的时机。