PAT甲級:1036 Boys vs Girls (25分)

PAT甲級: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**Fgrade**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函數,直接寫一個符合題意的cmp函數,使得數組開頭第一個就是女生最高分,最後一個是男生最低分。

然後就很簡單了~

至於cmp函數怎麼寫,先比較性別,男生往後排,女生往前排。性別相同時按成績從高到低排即可~

第二種方法也挺簡單,就搜索一遍數組找到男女生的最大值和最小值也可以,複雜度應該比直接排序要小~

這種就不說了,比較簡單,看看這種新奇點的方法能不能給自己帶來點啓發吧~

code

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct stu{
	string name;
	char sex;
	string ID;
	int grade;
};
bool cmp(stu a, stu b){//只需寫一個cmp函數即可~
	if(a.sex == b.sex) return a.grade > b.grade;
	return a.sex < b.sex;
}
void P(stu s, char sex){
	if(s.sex == sex) printf("%s %s\n", s.name.c_str(), s.ID.c_str());
	else printf("Absent\n");
}
int main(int argc, char** argv) {
	int n = 0, flag = 0;
	scanf("%d", &n);
	vector<stu> score(n);
	for(int i = 0; i < n; i++) score[i].name.resize(15), score[i].ID.resize(15);
	for(int i = 0; i < n; i++) scanf("%s %c %s %d", &score[i].name[0], &score[i].sex, &score[i].ID[0], &score[i].grade);
	sort(score.begin(), score.end(), cmp);
	if(!(score[0].sex == 'F' && score[score.size() - 1].sex == 'M')) flag = 1;
	P(score[0], 'F');
	P(score[score.size() - 1], 'M');
	if(flag) printf("NA\n");
	else printf("%d\n", score[0].grade - score[score.size() - 1].grade);
	return 0;
}

結果

提交時間 狀態 分數 題目 編譯器 耗時 用戶
2020/05/05 09:33:39 答案正確 25 1036 C++ (g++) 4 ms rash!
測試點 結果 耗時 內存
0 答案正確 3 ms 384 KB
1 答案正確 4 ms 384 KB
2 答案正確 3 ms 384 KB
3 答案正確 3 ms 384 KB
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章