b307中等

103 臺北市資訊學科能力競賽(2014)|領土

求全部安全哨的凸包面積並取整。

解題思路

求全部安全哨的凸包面積並取整。

按座標排序去重,建立下凸鏈與上凸鏈;新點使末三點非左轉時移除中間點,因它不可能成為該側凸包的必要頂點。

連接兩凸鏈得到按邊界排列的凸包。鞋帶公式中相鄰點叉積和的絕對值為兩倍面積。

整數座標使兩倍面積為整數,四捨五入到整數就是(A2+1)//2;小於三個凸包頂點面積0。

時間 O(n log n)次任意精度比較與叉積,空間 O(n)個座標;另計整數位數。

Step-by-step animation

單調鏈凸包與鞋帶公式逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

範例凸包四點(10,10)、(40,10)、(40,30)、(20,30)。

四個凸包頂點
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
struct Pt {
    cpp_int x, y;
    bool operator<(const Pt &b) const {
        return x != b.x ? x < b.x : y < b.y;
    }
    bool operator==(const Pt &b) const {
        return x == b.x && y == b.y;
    }
};
cpp_int cross(Pt a, Pt b, Pt c) {
    return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
vector<Pt> hull(vector<Pt> a) {
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
    if (a.size() < 3)
        return a;
    vector<Pt> h;
    for (Pt p : a) {
        while (h.size() > 1 && cross(h[h.size() - 2], h.back(), p) <= 0)
            h.pop_back();
        h.push_back(p);
    }
    size_t l = h.size();
    for (int i = (int)a.size() - 2; i >= 0; i--) {
        Pt p = a[i];
        while (h.size() > l && cross(h[h.size() - 2], h.back(), p) <= 0)
            h.pop_back();
        h.push_back(p);
    }
    h.pop_back();
    return h;
}
int main() {
    int n;
    cin >> n;
    vector<Pt> a(n);
    for (auto &p : a)
        cin >> p.x >> p.y;
    auto h = hull(a);
    cpp_int sum = 0;
    for (int i = 0; i < (int)h.size(); i++) {
        Pt p = h[i], q = h[(i + 1) % h.size()];
        sum += p.x * q.y - p.y * q.x;
    }
    if (sum < 0)
        sum = -sum;
    cout << (sum + 1) / 2 << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多