a912困難

98 全國資訊學科能力競賽(2009)|景觀餐廳

以每條逆時針邊的左半平面保留交集。

解題思路

凸多邊形內部位於每條逆時針邊的左側。以土地多邊形為目前圖形,逐條舊廠址邊裁切;每段按起終點在半平面內外,保留內點並在穿越時加入直線交點。

每輪保留的圖形恰是前一圖形與該半平面的交集,依歸納最後就是兩多邊形交集。用鞋帶公式計算面積。兩語言皆採有理數,最後由分子分母整數四捨五入,避免交點與小數恰半的浮點誤差。

若交集過程頂點上限為V≤M+N,O(NV)次有理數運算,空間O(V)個有理數;分子分母位數影響運算成本。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。

Step-by-step animation

教學示意(以步驟描述中的輸入為準)

回報動畫錯誤
步驟 1 / 3

示意兩正方形

A=[0,2]²、B=[1,3]²。

A面積4
B面積4
交集非空
是

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
#include <boost/rational.hpp>
using Q = boost::rational<cpp_int>;
struct P {
    Q x, y;
};
Q cross(P a, P b, P c) {
    return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
int main() {
    int m, n;
    cin >> m;
    vector<P> a(m);
    for (auto &p : a) {
        int x, y;
        cin >> x >> y;
        p = {Q(x), Q(y)};
    }
    cin >> n;
    vector<P> b(n);
    for (auto &p : b) {
        int x, y;
        cin >> x >> y;
        p = {Q(x), Q(y)};
    }
    for (int k = 0; k < n; k++) {
        vector<P> c;
        P u = b[k], v = b[(k + 1) % n];
        for (int i = 0; i < (int)a.size(); i++) {
            P s = a[i], t = a[(i + 1) % a.size()];
            Q ds = cross(u, v, s), dt = cross(u, v, t);
            if (ds >= Q(0))
                c.push_back(s);
            if ((ds < Q(0) && dt > Q(0)) || (ds > Q(0) && dt < Q(0))) {
                Q f = ds / (ds - dt);
                c.push_back({s.x + (t.x - s.x) * f, s.y + (t.y - s.y) * f});
            }
        }
        a = c;
    }
    Q area;
    for (int i = 0; i < (int)a.size(); i++)
        area += a[i].x * a[(i + 1) % a.size()].y - a[i].y * a[(i + 1) % a.size()].x;
    if (area < Q(0))
        area = -area;
    area /= Q(2);
    cpp_int num = area.numerator() * 100, den = area.denominator(), q = num / den;
    if (2 * (num % den) >= den)
        q++;
    cout << q / 100 << '.' << setw(2) << setfill('0') << (q % 100).convert_to<int>()
         << '\n';
}

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

更多