# 0-18 pair 講義不是我寫的,網址在此 https://emanlaicepsa.github.io/2020/10/21/0-index/ 我只是將自己寫的練習題程式碼記錄下來。 最後更新日期:2024年10月7日 ## [ZeroJudge: a915. 二維點排序](https://zerojudge.tw/ShowProblem?problemid=a915) ### Python 程式碼 執行時間最久約為 24 ms,使用記憶體最多約為 3.8 MB,通過測試。 ```python= n = int(input()) points = [] for _ in range(n): points.append(list(map(int, input().split()))) points.sort() for point in points: print(*point) ``` 也可以將程式碼第2到6行合併成以下程式碼的第2行,但是這樣對初學者而言不容易讀懂,以下詳細說明這行程式碼的功能。 1. 用 input() 讀取一行字串。 2. 用 split() 將字串以空格分開。 3. 將分開後的資料丢入 map 轉換成 int。 4. 用 tuple() 將轉換後的 int 組成 tuple。 5. 用方括號後方的 for 迴圈執行以上步驟 n 次。 6. n 組 tuple 組成 list。 7. 用 sorted() 將 list 由小到大排序。 8. 將排序後的 list 存到 points。 執行時間最久約為 22 ms,使用記憶體最多約為 3.7 MB,通過測試。 ```python= n = int(input()) points = sorted([tuple(map(int, input().split())) for _ in range(n)]) for point in points: print(*point) ``` ### C++ 程式碼 執行時間最久約為 3 ms,使用記憶體最多約為 344 kB,通過測試。 ```cpp= #include <iostream> #include <algorithm> #include <utility> using namespace std; int main() { ios::sync_with_stdio(0),cin.tie(0); int n; cin >> n; pair<int, int> points[n]; for(int i=0; i<n; i++) cin >> points[i].first >> points[i].second; sort(points, points+n); for(int i=0; i<n; i++) cout << points[i].first << " " << points[i].second << "\n"; return 0; } ``` ------ ###### tags:`演算法`、`APCS`、`Python`、`C++`