某小学最近得到了一笔赞助,打算拿出其中一部分为学习成绩优秀的前5名学生发奖学金。每个学生都有3门课的成绩:语文、数学、英语。先按总分从高到低排序,如果两个同学总分相同,再按语文成绩从高到低排序,如果两个同学总分和语文成绩都相同,那么规定学号小的同学排在前面,这样,每个学生的排序是唯一确定的。
任务:先根据输入的3门课的成绩计算总分,然后按上述规则排序,最后按排名顺序输出前五名名学生的学号和总分。注意,在前5名同学中,每个人的奖学金都不相同,因此,你必须严格按上述规则排序。例如,在某个正确答案中,如果前两行的输出数据(每行输出两个数:学号、总分) 是:
7 279
5 279
这两行数据的含义是:总分最高的两个同学的学号依次是7号、5号。这两名同学的总分都是 279 (总分等于输入的语文、数学、英语三科成绩之和) ,但学号为7的学生语文成绩更高一些。如果你的前两名的输出数据是:
5 279
7 279
则按输出错误处理,不能得分。
#include<iostream>
using namespace std;
struct Student{
int num;
int chinese;
int math;
int english;
int add;
};
void exchange(struct Student &a,struct Student &b){
struct Student temp=a;
a=b;
b=temp;
return;
}
int main(){
int n;
cin>>n;
struct Student s[n];
for(int i;i<n;i++){
s[i].num=i+1;
cin>>s[i].chinese>>s[i].math>>s[i].english;
s[i].add=s[i].chinese+s[i].math+s[i].english;
}
for(int i;i<n;i++){
for(int j;j<n-i;j++){
if(s[j].add<s[j+1].add||s[j].add==s[j+1].add,s[j].chinese<s[j+1].chinese||
s[j].add==s[j+1].add,s[j].chinese==s[j+1].chinese,s[j].num>s[j+1].num){
exchange(s[j],s[j+1]);
}
}
}
for(int i;i<5;i++){
cout<<s[i].num<<" "<<s[i].add<<endl;
}
return 0;
}
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<tuple<int, int, int, int, int>> a;
for (int i = 1; i <= n; i++)
{
int chinese, math, english, total;
cin >> chinese >> math >> english;
total = chinese + math + english;
a.push_back({i, chinese, math, english, total});
}
sort(a.begin(), a.end(), [](const auto &lhs, const auto &rhs) {
const auto& [no1, chinese1, math1, english1, total1] = lhs;
const auto& [no2, chinese2, math2, english2, total2] = rhs;
if (total1 != total2) return total1 > total2;
if (chinese1 != chinese2) return chinese1 > chinese2;
return no1 < no2;
});
int i = 0;
for (const auto &[no, chinese, math, english, total] : a)
{
cout << no << ' ' << total << '\n';
if (++i == 5)
break;
}
return 0;
}