日期:2026年4月28日
ZeroJudge 題目連結:d190. 11462 - Age Sort
解題想法
這題就是單純的排序,只是改成多組測資,以 0 結尾。如果用 Python 解題,可以先將 $n$ 個數字存入串列 arr,再用 arr.sort() 由小到大排序,最後用 print(*arr) 輸出;也可以用 sorted 將 map 轉換後的結果排序並用 print 輸出。如果想要測試一些特別的寫法,也可以用最小優先佇列解題,依序彈出佇列中的最小值,但其實這樣寫比較慢,對本題而言沒有必要。
Python 程式碼
使用時間約為 0.5 s,記憶體約為 157.1 MB,通過測試。
while True:
n = int(input())
if n == 0: break
arr = list(map(int, input().split()))
arr.sort()
print(*arr)
使用時間約為 0.5 s,記憶體約為 157.3 MB,通過測試。
while True:
n = int(input())
if n == 0: break
print(*sorted(map(int, input().split())))
用 sys.stdin 及 sys.stdout.write 加速,使用時間約為 0.4 s,記憶體約為 304.3 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
n = int(data[ptr])
ptr += 1
if n == 0: break
arr = sorted(map(int, data[ptr:ptr+n]))
ptr += n
res = " ".join(map(str, arr))
result.append(f"{res}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
heapq,反而更慢。使用時間約為 1.1 s,記憶體約為 157.4 MB,通過測試。
import heapq
while True:
n = int(input())
if n == 0: break
pq = [i for i in map(int, input().split())]
heapq.heapify(pq)
while len(pq) > 1: print(heapq.heappop(pq), end=" ")
print(heapq.heappop(pq))
C++ 程式碼
使用時間約為 0.2 s,記憶體約為 10.4 MB,通過測試。
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while(scanf("%d", &n) != EOF && n != 0) {
vector<int> arr (n);
for(int i=0; i<n; i++) scanf("%d", &arr[i]);
sort(arr.begin(), arr.end());
for(int i=0; i<n-1; i++) printf("%d ", arr[i]);
printf("%d\n", arr[n-1]);
}
return 0;
}
使用時間約為 0.3 s,記憶體約為 11 MB,通過測試。
#include <cstdio>
#include <queue>
#include <functional>
using namespace std;
int main() {
int n;
while(scanf("%d", &n) != EOF && n != 0) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int i=0; i<n; i++) {
int x; scanf("%d", &x);
pq.push(x);
}
while(pq.size() > 1) {
printf("%d ", pq.top());
pq.pop();
}
printf("%d\n", pq.top());
}
return 0;
}
沒有留言:
張貼留言