首页 > 其他 > 详细

7-4 宿舍谁最高?

时间:2018-10-23 12:59:40      阅读:1181      评论:0      收藏:0      [点我收藏+]

学校选拔篮球队员,每间宿舍最多有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;
    }
}

 

7-4 宿舍谁最高?

原文:https://www.cnblogs.com/x-huihui/p/9835587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!