PTA——宿舍谁最高7-1 宿舍谁最高? (20 分)
学校选拔篮球队员,每间宿舍最多有4个人。现给出宿舍列表,请找出每个宿舍最高的同学。定义一个学生类Student,有身高height,体重weight等。
输入格式:
首先输入一个整型数n (1<=n<=1000000),表示n位同学。
紧跟着n行输入,每一行格式为:宿舍号,name,height,weight。
宿舍号的区间为[0,999999], name 由字母组成,长度小于16,height,weight为正整数。
输出格式:
按宿舍号从小到大排序,输出每间宿舍身高最高的同学信息。题目保证每间宿舍只有一位身高最高的同学。
输入样例:
7
000000 Tom 175 120
000001 Jack 180 130
000001 Hale 160 140
000000 Marry 160 120
000000 Jerry 165 110
000003 ETAF 183 145
000001 Mickey 170 115
输出样例:
000000 Tom 175 120
000001 Jack 180 130
000003 ETAF 183 145
wa :
#include<iostream>
#include<string>
using namespace std;
class student
{
public:
float fight;
float weight;
string num;
string name;
public:
void input();
void output();
};
void student::input()
{
cin>>num>>name>>fight>>weight;
getchar();
}
void student::output()
{
cout<<num<<" "<<name<<" "<<fight<<" "<<weight<<endl ;
}
void sort(student *c,int n)
{
student temp;
for(int i=0;i<n-1;++i)
{
for(int j=i;j<n-1-i;++j)
{
if(c[j].num>c[j+1].num)
{
temp=c[j];
c[j]=c[j+1];
c[j+1]=temp;
}
}
}
}
student sorts(student *c,int z,int n)
{
student temp=c[z];
for(int i=z+1;i<n+z;++i)
{
if(c[i].fight>temp.fight)
{
temp=c[i];
}
}
return temp;
}
int main()
{
int n,i;
student *std=NULL;
cin>>n;
getchar();
std = new student[n+1];
//cout<<"hello"<<endl;
for(i=0;i<n;++i)
{
std[i].input();
}
std[i].name ="0000";
std[i].num ="-9999";
std[i].fight=-99;
std[i].weight =-99;
if(n>1)
{
sort(std,n);
student temp;
int flag=1;
for(i=0;i<n;++i)
{
if(std[i].num ==std[i+1].num )
{
flag++;
}
else
{
temp=sorts(std,i-flag+1,flag);
temp.output();
flag=1;
}
}
}
else
{
std[0].output();
}
return 0;
}
一开始采用string来存放宿舍号其实是不对的,比如:宿舍号为"1"与“23”的,如果输入“1”,“023”,则 “1”>“23”
AC:
#include<iostream>
#include<string>
#include<stdio.h>
#include<iomanip>
using namespace std;
class student
{
public:
float fight;
float weight;
int num;
string name;
public:
void input();
void output();
};
void student::input()
{
cin>>num>>name>>fight>>weight;
getchar();
}
void student::output()
{
cout<<setw(6)<<setfill('0')<<num;
cout<<" "<<name<<" "<<fight<<" "<<weight<<endl ;
}
void sort(student *c,int n)
{
student temp;
for(int i=0;i<n-1;++i)
{
for(int j=i;j<n-1-i;++j)
{
if(c[j].num>c[j+1].num)
{
temp=c[j];
c[j]=c[j+1];
c[j+1]=temp;
}
}
}
}
student sorts(student *c,int z,int n)
{
student temp=c[z];
for(int i=z+1;i<n+z;++i)
{
if(c[i].fight>temp.fight)
{
temp=c[i];
}
}
return temp;
}
int main()
{
int n,i;
student *std=NULL;
cin>>n;
getchar();
std = new student[n+1];
//cout<<"hello"<<endl;
for(i=0;i<n;++i)
{
std[i].input();
}
std[i].name ="0000";
std[i].num =-99999;
std[i].fight=-99;
std[i].weight =-99;
if(n>1)
{
sort(std,n);
student temp;
int flag=1;
for(i=0;i<n;++i)
{
if(std[i].num ==std[i+1].num )
{
flag++;
}
else
{
temp=sorts(std,i-flag+1,flag);
temp.output();
flag=1;
}
}
}
else
{
std[0].output();
}
return 0;
}