日期:2025年11月10日
ZeroJudge 題目連結:h075. 成績排名
解題想法
這題輸出的加權平均可能是小數或整數,因為分母是10,如果是小數則印出到小數點後一位。由於題目要求的比序依序為加權平均、資訊、數學、英文成績由高到低,如果前面4項成績相同,再依照座號由小到大排序,如果使用 Python,可以將每個人的加權平均、資訊、數學、英文、座號的負值等5項組成 tuple 存到串列當中,用 sort 排序串列時會自動依照 tuple 之中的數值由小到大排序。如果使用 C++,可以用vector 儲存每個人資料,也可以自訂結構體,不過這樣就需要自己寫排序用的比較式。
Python 程式碼
使用時間約為 43 ms,記憶體約為 3.3 MB,通過測試。
n = int(input())
students = [] # (tot, cs, math, english, -num)
for _ in range(n):
num, cs, math, english = list(map(int, input().split()))
tot = cs*5 + math*3 + english*2
students.append((tot, cs, math, english, -num))
students.sort(reverse=True)
for student in students:
tot, num = student[0], -student[4]
if tot%10 == 0: print(f"{num:d} {tot//10:d}")
else: print(f"{num:d} {tot/10:.1f}")
C++ 程式碼
使用時間約為 2 ms,記憶體約為 284 kB,通過測試。
#include <cstdio>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
int n; scanf("%d", &n);
vector<vector<int>> students (n, vector<int> (5)); // (tot, cs, math, english, -num)
for(int i=0; i<n; i++) {
int num, cs, math, english;
scanf("%d %d %d %d", &num, &cs, &math, &english);
int tot = cs*5 + math*3 + english*2;
students[i][0] = tot;
students[i][1] = cs;
students[i][2] = math;
students[i][3] = english;
students[i][4] = -num;
}
sort(students.begin(), students.end(), greater<vector<int>> ());
for(int i=0; i<n; i++) {
int tot = students[i][0], num = -students[i][4];
if (tot%10 == 0) printf("%d %d\n", num, tot/10);
else printf("%d %.1f\n", num, 1.0*tot/10.0);
}
return 0;
}
自訂結構體,使用時間約為 2 ms,記憶體約為 92 kB,通過測試。
#include <cstdio>
#include <algorithm>
using namespace std;
struct Student {
int tot, cs, math, english, num;
};
int main() {
int n; scanf("%d", &n);
Student students[n]; // (tot, cs, math, english, num)
for(int i=0; i<n; i++) {
int num, cs, math, english;
scanf("%d %d %d %d", &num, &cs, &math, &english);
int tot = cs*5 + math*3 + english*2;
students[i].num = num;
students[i].tot = tot;
students[i].cs = cs;
students[i].math = math;
students[i].english = english;
}
sort(students, students+n, [] (Student a, Student b) {
if (a.tot == b.tot) {
if (a.cs == b.cs) {
if (a.math == b.math) {
if (a.english == b.english) {
return a.num < b.num;
} else {
return a.english > b.english;
}
} else {
return a.math > b.math;
}
} else {
return a.cs > b.cs;
}
} else {
return a.tot > b.tot;
}
} );
for(int i=0; i<n; i++) {
int tot = students[i].tot, num = students[i].num;
if (tot%10 == 0) printf("%d %d\n", num, tot/10);
else printf("%d %.1f\n", num, 1.0*tot/10.0);
}
return 0;
}
沒有留言:
張貼留言