【通过PAT复习C++与数据结构】PAT-A 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.

输入描述:
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.

输出描述:
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.
示例1
输入
3
Joe M Math990112 89
Mike M CS991301 100
Mary F EE990830 95
输出
Mary EE990830
Joe Math990112
6

解题思路

这道题思路很简单(虽然是一道25分的题目),和甲级题目相比,就是代码量大了一些,没有用到算法,基本逻辑就可以解决

  • 我的代码完全可以化简。但是我想留下我最初的思考,不去改动了,也有利于读者能够理解我刷代码时最初的思路。

代码

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;
typedef struct stu{
	string name;
	int male=0;//默认0为男性,1为女性;
	string ID;
	int score; 
}stu;

int main() {
	stu all[10010];
	stu male[10010]; 
	stu female[10010];
	int N;
	cin>>N;
	for(int i=0;i<N;++i){
		cin>>all[i].name;
		string in_male;
		cin>>in_male;
		if(in_male!="M")all[i].male=1;//如果不是男性就是女性了
		cin>>all[i].ID;
		cin>>all[i].score; 
	}
	//下面把男性和女性分开保存到两个数组中
	int p=0,q=0;//用于追踪男性和女性数组下标 
	for(int i=0;i<N;++i){
		if(all[i].male==0)male[p++]=all[i];
		else female[q++]=all[i];
	} 
	
	//对两个数组进行排序,找出男性最小值和女性最大值,这里无需使用sort函数,因为只需要找出最值即可 
	 //找出女性最大值,并输出 
	  
	 int max=10001;
	 female[max].score=-1;
	 for(int i=0;i<q;++i){
		if(female[i].score>female[max].score)max=i;
	 } 

	 if(max!=10001)	cout<<female[max].name<<" "<<female[max].ID<<endl;
	 else cout<<"Absent"<<endl;

	 //接下来开始找出男性最小值了
	 int min=10001;
	 male[min].score=101;
	 for(int i=0;i<p;++i){
	 	
		if(male[i].score<male[min].score)min=i;
	 } 
 
	 if(min!=10001)	cout<<male[min].name<<" "<<male[min].ID<<endl;
	 else cout<<"Absent"<<endl;
	 
	 //输出两者之间的差值

	 if(min!=10001&&max!=10001)cout<<female[max].score -male[min].score; 
	 else cout<<"NA"; 
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值