1. 程式人生 > >CCF NOI1042. 發獎學金 (C++)

CCF NOI1042. 發獎學金 (C++)

1042. 發獎學金

題目描述

某小學最近得到了一筆贊助,打算拿出其中一部分為學習成績優秀的前5名學生髮獎學金。期末,每個學生都有3門課的成績:語文、數學、英語。先按總分從高到低排序,如果兩個同學總分相同,再按語文成績從高到低排序,如果兩個同學總分和語文成績都相同,那麼規定學號小的同學排在前面,這樣,每個學生的排序是唯一確定的。

任務:先根據輸入的3門課的成績計算總分,然後按上述規則排序,最後按排名順序輸出前五名名學生的學號和總分。注意,在前5名同學中,每個人的獎學金都不相同,因此,你必須嚴格按上述規則排序。例如,在某個正確答案中,如果前兩行的輸出資料(每行輸出兩個數:學號、總分) 是:
7 279
5 279
這兩行資料的含義是:總分最高的兩個同學的學號依次是7號、5號。這兩名同學的總分都是 279 (總分等於輸入的語文、數學、英語三科成績之和) ,但學號為7的學生語文成績更高一些。如果你的前兩名的輸出資料是:
5 279
7 279
則按輸出錯誤處理,不能得分。

輸入

包含n+1行: 第1行為一個正整數n,表示該校參加評選的學生人數。
第2到n+1行,每行有3個用空格隔開的數字,每個數字都在0到100之間。第j行的3個數字依次表示學號為 j-1 的學生的語文、數學、英語的成績。每個學生的學號按照輸入順序編號為1~n (恰好是輸入資料的行號減1)。所給的資料都是正確的,不必檢驗。

輸出

共有5行,每行是兩個用空格隔開的正整數,依次表示前5名學生的學號和總分。

樣例輸入

6
90 67 80
87 66 91
78 89 91
88 99 77
67 89 64
78 89 98

樣例輸出

6 265
4 264
3 258
2 244
1 237

資料範圍限制

50%的資料滿足:各學生的總成績各不相同;
100%的資料滿足: 6<=n<=300。

C++程式碼

#include <iostream>
#include <cassert>
#include <algorithm>

using namespace std;

const int N = 300; // maximum n

// define a new struct type Student
struct _Student
{
    int ID;
    int Chinese; 
    int Math;
int English; int total; }; typedef struct _Student Student; // define my sorting criteria function int cmp(const void *s1, const void *s2) { if (((Student *)s1)->total == ((Student *)s2)->total) { if (((Student *)s1)->Chinese == ((Student *)s2)->Chinese) { // sort ascending by Student ID return ((Student *)s1)->ID - ((Student *)s2)->ID; } else { // sort descending by Chinese score return ((Student *)s2)->Chinese - ((Student *)s1)->Chinese; } } else { // sort descending by total score return ((Student *)s2)->total - ((Student *)s1)->total; } } int main() { int n; cin >> n; assert(6 <= n && n <= N); Student s; Student AllStudents[N]; for(int i=1; i<=n; i++) { cin >> s.Chinese >> s.Math >> s.English; assert(0 <= s.Chinese && s.Chinese <= 150); assert(0 <= s.Math && s.Math <= 150); assert(0 <= s.English && s.English <= 150); s.ID = i; s.total = s.Chinese + s.Math + s.English; AllStudents[i-1] = s; } qsort(AllStudents, n, sizeof(Student), cmp); for(int i=1; i<=5; i++) { cout << AllStudents[i-1].ID << " " << AllStudents[i-1].total << endl; } return 0; }