題目
Description
Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings. The entire horizon is represented by a number line with N (1 <= N <= 40,000) buildings. Building i’s silhouette has a base that spans locations A_i through B_i along the horizon (1 <= A_i < B_i <= 1,000,000,000) and has height H_i (1 <= H_i <= 1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by all N buildings.
N個矩形塊,交求面積並.
Input
-
Line 1: A single integer: N
-
Lines 2…N+1: Input line i+1 describes building i with three space-separated integers: A_i, B_i, and H_i
Output
- Line 1: The total area, in square units, of the silhouettes formed by all N buildings
Sample Input
4
2 5 1
9 10 4
6 8 2
4 6 3
Sample Output
16
OUTPUT DETAILS:
The first building overlaps with the fourth building for an area of 1
square unit, so the total area is just 31 + 14 + 22 + 23 – 1 = 16.
思路
掃描線 線段樹。
題中建築物不可能在半空中,所以我們可以減少記錄的內容。
上代碼。
代碼
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 80010;
int n, tot, yi[N];
struct node{ll ff, x, ya, yb;} li[N];
struct nd{
ll ml, mr, s, len;
int l, r;
} t[N*4];
bool cmp(const node &a, const node &b) {
return a.x < b.x;
}
void build(int bh, int l, int r) {
t[bh].l = l; t[bh].r = r;
t[bh].ml = yi[l]; t[bh].mr = yi[r];
t[bh].s = t[bh].len = 0;
if (t[bh].r-t[bh].l == 1) return;
int mid = (l+r)/2;
build(bh*2, l, mid);
build(bh*2+1, mid, r);
}
void update(int bh) {
if (t[bh].s > 0) t[bh].len = t[bh].mr-t[bh].ml;
else if (t[bh].r-t[bh].l == 1) t[bh].len = 0;
else t[bh].len = t[bh*2].len+t[bh*2+1].len;
return;
}
void add(int bh,node b) {
if (t[bh].ml == b.ya && t[bh].mr == b.yb) {
t[bh].s+=b.ff;
update(bh);
return;
}
if (b.yb <= t[bh<<1].mr) add(bh*2, b);
else if (b.ya >= t[bh*2+1].ml) add(bh*2+1, b);
else {
node tmp = b;
tmp.yb=t[bh*2].mr;
add(bh*2,tmp);
tmp=b;
tmp.ya=t[bh*2+1].ml;
add(bh*2+1, tmp);
}
update(bh);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
ll u, w, z;
scanf("%lld%lld%lld",&u,&w,&z);
tot++; yi[i] = z;
li[tot].x = u; li[tot].ya = 0; li[tot].yb = z; li[tot].ff = 1;
li[++tot].x = w; li[tot].ya = 0; li[tot].yb = z; li[tot].ff = -1;
}
yi[n+1] = 0;
sort(yi+1, yi+2+n);
sort(li+1, li+1+tot, cmp);
build(1, 1, n+1);
add(1, li[1]);
ll sum = 0;
for (int i = 2; i <= tot; i++) {
sum += t[1].len*(li[i].x-li[i-1].x);
add(1, li[i]);
}
printf("%lld", sum);
return 0;
}