题目链接:P5740 【深基7.例9】最厉害的学生 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目描述
现有 N(N <= 1000)名同学参加了期末考试,并且获得了每名同学的信息:姓名(不超过 8 个字符的仅有英文小写字母的字符串)、语文、数学、英语成绩(均为不超过 150 的自然数)。总分最高的学生就是最厉害的,请输出最厉害的学生各项信息(姓名、各科成绩)。如果有多个总分相同的学生,输出靠前的那位。
输入格式
无
输出格式
无
样例 #1
样例输入 #1
- 3
- senpai 114 51 4
- lxl 114 10 23
- fafa 51 42 60
样例输出 #1
senpai 114 51 4
本题主要考察struct结构体和sort排序。
AC code:
- #include<iostream>
- #include<algorithm>
-
- using namespace std;
-
- struct st // 定义一个结构体st
- {
- int id; // 编号
- string name; // 姓名
- int Ch; // 语文
- int Ma; // 数学
- int Eng; // 英语
- int total; // 总分
-
- };
-
- bool cmp(st a,st b)
- {
- if(a.total>b.total)
- return true;
- else if(a.total==b.total && a.id<b.id)
- return true;
- else
- return false;
- }
-
- /* 与上面cmp函数等价,两种cmp函数任选其一
- bool cmp(st a,st b)
- {
- if(a.total==b.total)
- return a.id<b.id;
- else
- return a.total>b.total;
- }*/
-
- int main()
- {
- int n;
- cin>>n;
- struct st s[n]; // 定义一个结构体数组s
- for(int i=0;i<n;i++)
- {
- s[i].id=i;
- cin>>s[i].name>>s[i].Ch>>s[i].Ma>>s[i].Eng;
- s[i].total=s[i].Ch+s[i].Ma+s[i].Eng;
- }
- sort(s,s+n,cmp); // 调用sort函数进行快速排序
-
- cout<<s[0].name<<" "<<s[0].Ch<<" "<<s[0].Ma<<" "<<s[0].Eng<<endl;
-
- return 0;
- }