vector PTA 7-10 宿舍谁最高?

7-10 宿舍谁最高? (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

思路:

  1. 定义学生类,包含身高,体重,名字,宿舍号等变量,定义展示函数。
  2. 读入一个学生的信息,在vector中查找该学生宿舍号,不存在则将该学生插入到vector中,若存在则比较当前宿舍最高身高和该学生身高,并进行替换/保留处理。
  3. 通过定义比较函数,按从宿舍号从小到大排序,并遍历输出学生信息。

代码:

#include <bits/stdc++.h>
using namespace std;
struct Student{
    int height=0;
    int sushehao;
    int weight;
    string name;
    void show(){
        cout<<setw(6)<<setfill('0')<<sushehao<<" "<<name<<" "<<height<<" "<<weight<<endl;
    }
};
bool cmp(Student a,Student b);
int isExist(vector<Student>a,int h);
int main() {
    vector<Student>a;
    int n,h,k,l;
    string x;
    cin>>n;
    for (int i = 0; i < n; ++i) {
        cin>>h>>x>>k>>l;
        Student tmp;
        tmp.height=k;
        tmp.weight=l;
        tmp.name=x;
        tmp.sushehao=h;
        int g=isExist(a,h);
        if(g!=-1)
        {
            if(a[g].height<k)
            {
                a.erase(a.begin()+g);
                a.push_back(tmp);
            }
        }
        else{a.push_back(tmp);}
    }
    sort(a.begin(),a.end(),cmp);
    for (int j = 0; j < a.size(); ++j) {
        a[j].show();
    }
    return 0;
}
bool cmp(Student a,Student b)
{
    return a.sushehao<b.sushehao;
}
int isExist(vector<Student>a,int h)
{
    for (int i = 0; i < a.size(); ++i) {
        if(a[i].sushehao==h)return i;
    }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/qq_46039856/article/details/106500318