# Sorting# Standard Input# Standard Output

d323 - 電腦-窮人的

🔗 前往 ZeroJudge 原題

題目描述

題目要求讀取一組正整數,將其排序後輸出。輸入的第一行是數字的個數 N,接下來的 N 行是需要排序的數字。數字不重複,且都在 int 範圍內。由於記憶體限制,需要注意效率。

解題思路

這題的解題思路非常直接:讀取輸入,使用標準庫的 sort 函數進行排序,然後輸出排序後的結果。由於題目限制記憶體為 32000 KB,且 N 最大可達一千萬,因此需要注意輸入和輸出效率,避免不必要的記憶體佔用。使用 std::ios::sync_with_stdio(false);cin.tie(NULL); 可以提高輸入輸出的速度。

複雜度分析

  • 時間複雜度: O(N log N) (主要來自 sort 函數)
  • 空間複雜度: O(N) (主要來自儲存輸入數字的陣列 b)

程式碼

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
	std::ios::sync_with_stdio(false);
    cin.tie(NULL);
	int a;
	while(cin >> a){
		int b[a];
		for(int i=0;i<a;i++){
			cin >> b[i];
		}
		sort(b,b+a);
		for(int i=0;i<a;i++){
			cout << b[i] << " ";
		}
	}
}

Discussion