跳到正文

题解

题解:P1093 [NOIP2007 普及组] 奖学金

wsx2012约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年7月8日
收录
2026年7月8日
更新
2026年11月14日
篇幅
约 3 分钟
题目
P1093

版本

  1. v2当前
  2. v1

题目传送门

题意

输入 nn 个学生的语、数、英三门成绩,按下列规则排序:

  1. 总分高的在前。
  2. 若总分相同,则语文成绩高的在前。
  3. 若语文成绩相同,则学号(即输入次序)小的在前。

思路

首先,我们可以使用 C++ 中的struct来定义结构体类型:

C++
struct stu{
    int id;//学号
    int chinese;//语文成绩
    int math;//数学成绩
    int english;//英语成绩
    int all;//总分
};

其次,我们可以用 sort 来对学生成绩进行排序。

但是, sort 无法直接对结构体进行排序。

这时,我们可以在结构体中重载 << 运算符:

C++
bool operator <(const stu oth)const{
    if(all!=oth.all) return all>oth.all;//按总分降序排序
    if(chinese!=oth.chinese) return chinese>oth.chinese;//按语文成绩降序排序
    return id<oth.id;//按学号升序排序
}

然后在主程序中写上: sort(stus,stus+n); 或 sort(stus.begin(),stus.end()) 即可!

AC代码
C++
#include<bits/stdc++.h>
using namespace std;
struct stu{
    int id,chi,mat,eng,all;
    void input(){
        cin>>chi>>mat>>eng;
        all=chi+mat+eng;
    }
    void output(){
        cout<<id<<' '<<all<<endl;
    }
    bool operator <(const stu oth)const{
        if(all!=oth.all) return all>oth.all;
        if(chi!=oth.chi) return chi>oth.chi;
        return id<oth.id;
    }
};
int main(){
    int n;
    cin>>n;
    vector<stu> stus(n);
    for(int i=0;i<n;i++){
        stus[i].id=i+1;
        stus[i].input();
    }
    sort(stus.begin(),stus.end());
    for(int i=0;i<5;i++) stus[i].output();
    return 0;
}

AC记录

原文