1093 奖学金

1093 奖学金

难度:普及-

题目类型:模拟

提交次数:1

涉及知识:结构体,stable_sort

题目描述

某小学最近得到了一笔赞助,打算拿出其中一部分为学习成绩优秀的前5名学生发奖学金。期末,每个学生都有3门课的成绩:语文、数学、英语。先按总分从高到低排序,如果两个同学总分相同,再按语文成绩从高到低排序,如果两个同学总分和语文成绩都相同,那么规定学号小的同学 排在前面,这样,每个学生的排序是唯一确定的。

任务:先根据输入的3门课的成绩计算总分,然后按上述规则排序,最后按排名顺序输出前五名名学生的学号和总分。注意,在前5名同学中,每个人的奖学金都不相同,因此,你必须严格按上述规则排序。例如,在某个正确答案中,如果前两行的输出数据(每行输出两个数:学号、总分) 是:

7 279 5 279 这两行数据的含义是:总分最高的两个同学的学号依次是7号、5号。这两名同学的总分都是 279 (总分等于输入的语文、数学、英语三科成绩之和) ,但学号为7的学生语文成绩更高一些。如果你的前两名的输出数据是:

5 279 7 279 则按输出错误处理,不能得分。

代码:

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<vector>
 4 using namespace std;
 5 struct student{
 6     int num;
 7     int chn;
 8     int math;
 9     int eng;
10     int total = chn+math+eng;
11     student(int chnn = 0, int mathh = 0, int engg = 0):chn(chnn), math(mathh), eng(engg){}
12 };
13 bool comp(student stua, student stub){
14     if(stua.total!=stub.total)
15         return stua.total>stub.total;
16     else//if(stu.chn!=stu.chn) 
17         return stua.chn>stub.chn;
18     
19 }
20 int main(){
21     vector<student>stu;
22     int n, i;
23     cin>>n;
24     for(i = 0; i < n; i++){
25         int a, b, c;
26         cin>>a>>b>>c;
27         stu.push_back(student(a,b,c));
28         stu[i].num = i+1;
29     }
30     stable_sort(stu.begin(), stu.end(), comp);
31     for(i = 0; i < 5; i++){
32         cout<<stu[i].num<<" "<<stu[i].total<<endl;
33     }
34     return 0;
35 }

备注:

一道熟悉结构体和排序函数的题,按照老师讲的,因为输入顺序就是学号从小到大,所以用stable_sort进行排序,可是第一次把comp写错了,导致学号顺序换了,如注释所示。那么写,当两个if条件都不符合时应该咋比呢?等待老师解答中。另外还遇到了警告warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 (在C11标准或者gnu++11标准才支持这种方式初始化),就是第十行代码,我写的时候担心过会不会出问题,原来只有C11标准支持,要注意这一点。

原文地址:https://www.cnblogs.com/fangziyuan/p/5782723.html