【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b964
【Tag】多重迴圈、陣列、排序、STL sort
目錄
做法1: 泡沫排序法【筆記】
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
int best = -1; //不及格中最高分數
int worst = 101; //及格中最低分數
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] < 60) {
best = max(best, a[i]);
} else {
worst = min(worst, a[i]);
}
}
// Bubble Sort: 由小到大排序
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j ++) {
if (a[i] > a[j]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
//第一行由小而大印出所有成績,最後一個數字後無空白
for (int i = 0; i < n; i++) {
if (i) cout << " ";
cout << a[i];
}
cout << "\n";
//第二行印出最高不及格分數,如果全數及格時,於此行印出 best case
if (best < 0) {
cout << "best case\n";
} else {
cout << best << "\n";
}
//第三行印出最低及格分數,如果全數不及格時,於此行印出 worst case
if (worst > 100) {
cout << "worst case\n";
} else {
cout << worst << "\n";
}
return 0;
}
做法2: STL sort
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
int best = -1; //不及格中最高分數
int worst = 101; //及格中最低分數
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] < 60) {
best = max(best, a[i]);
} else {
worst = min(worst, a[i]);
}
}
// STL sort
sort(a, a + n);
//第一行由小而大印出所有成績,最後一個數字後無空白
for (int i = 0; i < n; i++) {
if (i) cout << " ";
cout << a[i];
}
cout << "\n";
//第二行印出最高不及格分數,如果全數及格時,於此行印出 best case
if (best < 0) {
cout << "best case\n";
} else {
cout << best << "\n";
}
//第三行印出最低及格分數,如果全數不及格時,於此行印出 worst case
if (worst > 100) {
cout << "worst case\n";
} else {
cout << worst << "\n";
}
return 0;
}
Python code
n = int(input())
scores = list(map(int, input().split())) #記錄所有學生分數的list
scores.sort() #由小到大排序
min_score = 101 #用來記錄及格者的最低分數
max_score = -1 #用來記錄及不及格者的最高分數
for score in scores:
if score >= 60: #及格
min_score = min(score, min_score)
else: #不及格
max_score = max(score, max_score)
print(' '.join(str(score) for score in scores))
if max_score == -1: #沒有人不及格
print('best case')
else:
print(max_score)
if min_score == 101: #沒有人及格
print('worst case')
else:
print(min_score)