熱門文章

2025年7月17日 星期四

ZeroJudge 解題筆記:a915. 二维点排序

作者:王一哲
日期:2025年7月17日


ZeroJudge 題目連結:a915. 二维点排序

解題想法


這題在 Python 先將座標 (x, y) 組成 tuple 再存入 list,再用 sort 將 list 排序。在 C++ 可以用 pair 或自訂 struct 儲存座標 (x, y),再存入 array 或 vector,再用 algorithm 函式庫的 sort 排序。

Python 程式碼


使用時間約為 23 ms,記憶體約為 3.8 MB,通過測試。
n = int(input())
arr = sorted([tuple(map(int, input().split())) for _ in range(n)])
for a in arr: print(*a)

使用時間約為 22 ms,記憶體約為 3.7 MB,通過測試。
n = int(input())
for a in sorted([tuple(map(int, input().split())) for _ in range(n)]): print(*a)


C++ 程式碼


使用時間約為 2 ms,記憶體約為 260 kB,通過測試。
#include <cstdio>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;

int main() {
    int n; scanf("%d", &n);
    vector<pair<int, int>> arr (n);
    for(int i=0; i<n; i++) {
        int x, y; scanf("%d %d", &x, &y);
        arr[i] = make_pair(x, y);
    }
    sort(arr.begin(), arr.end());
    for(auto a : arr) printf("%d %d\n", a.first, a.second);
    return 0;
}

使用時間約為 2 ms,記憶體約為 88 kB,通過測試。
#include <cstdio>
#include <algorithm>
using namespace std;

struct Point {
    int x, y;
};

int main() {
    int n; scanf("%d", &n);
    Point arr[n];
    for(int i=0; i<n; i++) {
        int x, y; scanf("%d %d", &x, &y);
        arr[i].x = x;
        arr[i].y = y;
    }
    sort(arr, arr+n, [](Point a, Point b) {
        if (a.x == b.x) return a.y < b.y;
        return a.x < b.x; } );
    for(int i=0; i<n; i++) printf("%d %d\n", arr[i].x, arr[i].y);
    return 0;
}


沒有留言:

張貼留言