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
题目大意:输入N个人的信息,包括名字,性别,ID 分数。要求输出分数最低的男生的名字,ID 以及分数最高的女生的名字,ID 并且求出女生最高分减男生最高分的差值。如果没有男生或女生的信息,则在相应行输出Absent,在差值的那行输出NA
思路:1.由于是求最高女生和最低男生,因此可先按照是否为男生排序,再按照分数由低到高或由高到低排序,这样队列的最前 端与最后端刚好是所求值。
2.由于F 在M的字典顺序前面,所以成绩按照由高到低排。数列的第一个为成绩最高的女生,最后一位为成绩最低的男 生,在输出之前检测性别以决定是否输出Absent 和NA
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct Person{
string name;
char gender;
string id;
int grade;
};
//输入数据
void input(vector<Person>&person){
int n;
cin>>n;
for(int i=0;i<n;i++){
Person temp;
cin>>temp.name>>temp.gender>>temp.id>>temp.grade;
person.push_back(temp);
}
}
//比较函数
int compare(Person &a,Person &b){
if(a.gender!=b.gender)
return a.gender<b.gender;
return a.grade>b.grade;
}
//检测第一位和最后一位的性别。
void computeResult(vector<Person> &result,vector<Person> &person){
if(person[0].gender=='F'){
result.push_back(person[0]);
}
if(person.back().gender=='M'){
result.push_back(person.back());
}
}
int main(){
vector<Person>person;
input(person);
sort(person.begin(),person.end(),compare);
vector<Person>result;
computeResult(result,person);
if(result.size()==2){
for(int i=0;i<2;i++){
cout<<result[i].name<<" "<<result[i].id<<endl;
}
cout<<result[0].grade-result[1].grade<<endl;
}
else if(result.size()==1){
if(result[0].gender=='F'){
cout<<result[0].name<<" "<<result[0].id<<endl;
cout<<"Absent"<<endl;
cout<<"NA"<<endl;
}
else if(result[0].gender=='M'){
cout<<"Absent"<<endl;
cout<<result[0].name<<" "<<result[0].id<<endl;
cout<<"NA"<<endl;
}
}
else{
cout<<"Absent"<<endl;
cout<<"Absent"<<endl;
cout<<"NA"<<endl;
}
}