7-4 宿舍誰最高?


學校選拔籃球隊員,每間宿舍最多有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

 

 

 

代碼實現

#include<iostream>
#include<map>
#include<string>
using namespace std;
class Student
{
public:
    string name;
    int h = 0;
    int w;
};

Student s[1000000];   //放在主函數中超范圍
int main()
{
    int n, p=0;
    cin >> n;
    bool isendl = false;
    map<int, Student>mp;
    int num;
    for (int i = 0; i < n; i++)
    {
        cin >> num;
        cin >> s[i].name >> s[i].h >> s[i].w;
        if (mp[num].h < s[i].h)
        {
            mp[num] = s[i];
        }
         
    }
    for (auto it=mp.begin();it!=mp.end();it++)
    {
        if (isendl) {
            cout << endl;
        }
        isendl = true;
        printf("%06d", it->first);
        cout << ' ' << it->second.name << ' ' << it->second.h << ' ' <<it->second.w;
    }
}

map容器詳解

map是模板,一個map變量key和value兩個值,你在這里是想用類似map<int,int> m_map的變量來表示背包里的東西,m_map->first可以取得key值,m_map->second可以取得value值;map自動按照key值按升序排列,key的值不能修改,可以修改value的值。

https://blog.csdn.net/lpstudy/article/details/11367285

 

 

 

之前不知道數組放在外面就不超范圍 

另一種解法

#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Student
{
public:
    int id;
    string name;
    int h = 0;
    int w;
};

Student s[1000000];
int main()
{
    int n, p = 0;
    cin >> n;
    for (int i = 0; i < 1000000; i++)      //因為宿舍號可能不是按順序排列的 比如000001 000003 000004  這樣
        s[i].id = i;

    Student stu;
    bool isendl = false;
    for (int i = 0; i < n; i++)
    {
        cin >> stu.id >> stu.name >> stu.h >> stu.w;
        if (stu.h > s[stu.id].h)
        {
            s[stu.id].name = stu.name;
            s[stu.id].h = stu.h;
            s[stu.id].w = stu.w;
            p++;
        }
    }
    for (int i = 0; i < 1000000; i++)
    {
        if (s[i].h == 0)
            continue;
        if (isendl) {
            cout << endl;
        }
        isendl = true;
        printf("%06d", s[i].id);
        cout << ' ' << s[i].name << ' ' << s[i].h << ' ' << s[i].w;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM