题目链接:http://www.patest.cn/contests/pat-a-practise/1036
题目:
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 95Sample Output 1:
Mary EE990830 Joe Math990112 6Sample Input 2:
1 Jean M AA980920 60Sample Output 2:
Absent Jean AA980920 NA
分析:
找到分数最高的女生和分数最低的男生的差值。
注意没有人(男生或女生)的情况。
AC代码:
#include<iostream> #include<stdio.h> #include<vector> #include<string> using namespace std; struct Student{ string name; char sex; string id; int grade; }; vector<Student> M;//男生 vector<Student> F;//女生 Student M_lowest;//分数最低的男生 Student F_highest;//分数最高的女生 int main(){ //freopen("F://Temp/input.txt", "r", stdin); int n; cin >> n; for (int i = 0; i < n; i++){ Student tmp; cin >> tmp.name >> tmp.sex >> tmp.id >> tmp.grade; if (tmp.sex == 'M')M.push_back(tmp); else F.push_back(tmp); } M_lowest.grade = 100; for (int i = 0; i < M.size(); i++){ if (M_lowest.grade > M[i].grade){ M_lowest = M[i]; } } F_highest.grade = 0; for (int i = 0; i < F.size(); i++){ if (F_highest.grade < F[i].grade){ F_highest = F[i]; } } if (M_lowest.grade == 100 && F_highest.grade == 0){//说明没有找到 cout << "Absent" << endl << "Absent" << endl << "NA" << endl; } else if (M_lowest.grade == 100){ cout << F_highest.name << " " << F_highest.id << endl << "Absent" << endl << "NA" << endl; } else if (F_highest.grade == 0){ cout << "Absent" << endl << M_lowest.name << " " << M_lowest.id << endl << "NA" << endl; } else {//都找到了 cout << F_highest.name << " " << F_highest.id << endl << M_lowest.name << " " << M_lowest.id << endl << F_highest.grade - M_lowest.grade << endl; } return 0; }
截图:
——Apie陈小旭