解題思路
將所有頂點y排序,對相鄰y形成的水平帶,在帶中央與所有垂直邊求交,排序x後兩兩配成草坪內部區間。這些區間在整個帶內維持不變。
若某個完整左右端點區間在上一帶仍存在,就延長原小草坪;否則從目前y開始建立新塊。上帶消失的區間則在此高度結束。這樣不會把不相關的遠處水平邊誤當成貫穿切線,又會在真正凹角導致左右界改變時切開。
完成後按每塊左下角(y,x)排序,計算編號、奇數總和與面積乘塊數≥總面積的條件,最後用編號查表回答子集合。
V個頂點的掃描時間 O(V² log V),空間 O(V²+SK)(本解讀取所有查詢);可串流降查詢空間。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
示意L形
頂點(0,0),(2,0),(2,1),(1,1),(1,2),(0,2)。
y:0,1,2
- 水平帶
- 2
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int>> p(n);
vector<int> ys;
for (auto &[x, y] : p) {
cin >> x >> y;
ys.push_back(y);
}
sort(ys.begin(), ys.end());
ys.erase(unique(ys.begin(), ys.end()), ys.end());
vector<array<long long, 4>> rect;
map<pair<int, int>, int> prev;
for (int h = 0; h + 1 < (int)ys.size(); h++) {
int y = ys[h], top = ys[h + 1];
vector<int> xs;
for (int i = 0; i < n; i++) {
auto [x1, y1] = p[i];
auto [x2, y2] = p[(i + 1) % n];
if (x1 == x2 && 2 * min(y1, y2) < y + top && y + top < 2 * max(y1, y2))
xs.push_back(x1);
}
sort(xs.begin(), xs.end());
map<pair<int, int>, int> now;
for (int i = 0; i + 1 < (int)xs.size(); i += 2) {
pair<int, int> key = {xs[i], xs[i + 1]};
int id;
if (prev.count(key)) {
id = prev[key];
rect[id][3] = top;
} else {
id = rect.size();
rect.push_back({xs[i], y, xs[i + 1], top});
}
now[key] = id;
}
prev = now;
}
sort(rect.begin(), rect.end(),
[](auto a, auto b) { return pair{a[1], a[0]} < pair{b[1], b[0]}; });
vector<long long> a;
long long total = 0, odd = 0, big = 0;
for (auto r : rect) {
long long v = (r[2] - r[0]) * (r[3] - r[1]);
a.push_back(v);
total += v;
if (a.size() % 2)
odd += v;
}
for (auto v : a)
if (v * (long long)a.size() >= total)
big += v;
cout << a.size() << '\n' << odd << '\n' << big << '\n';
int S, K;
cin >> S >> K;
while (S--) {
long long ans = 0;
for (int j = 0; j < K; j++) {
int x;
cin >> x;
ans += a[x - 1];
}
cout << ans << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。