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) N(1≤N≤40,000) buildings. Building i's silhouette has a base that spans locations Ai Ai through Bi Bi along the horizon (1≤Ai<Bi≤1,000,000,000) (1≤Ai<Bi≤1,000,000,000) and has height Hi(1≤Hi≤1,000,000,000) Hi(1≤Hi≤1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by all N N buildings.
Line 1: A single integer: N N
Lines 2→N+1 2→N+1: Input line i+1 i+1 describes building i i with three space-separated integers: Ai Ai, Bi Bi, and Hi Hi
Line 1: The total area, in square units, of the silhouettes formed by all N N buildings
4 2 5 1 9 10 4 6 8 2 4 6 3
16
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 <cstdio>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#define MAXN 2147483647
using namespace std;
struct line
{
long long f,l,r;
long long h;
friend bool operator < (line a,line b)
{
return a.h < b.h;
}
} yline[80008];
struct Segtree
{
long long l,r,cnt;
long long cover;
} tree[320006];
long long num,tot,n,a,b,h,xdis[80008],width[80008],ans;
unordered_map <long long,long long> f;
void build(long long i,long long l,long long r)
{
tree[i].l = l;
tree[i].r = r;
tree[i].cnt = 0;
if(l == r) return;
long long mid = (l+r)/2;
build(2*i,l,mid);
build(2*i+1,mid+1,r);
}
void deal(long long i,long long l,long long r,long long f)
{
if(l == tree[i].l && r == tree[i].r)
{
tree[i].cnt += f;
if(tree[i].cnt == 0)
{
if(l != r) tree[i].cover = tree[i*2].cover + tree[i*2+1].cover;
else tree[i].cover = 0;
}
else tree[i].cover = width[tree[i].r+1] - width[tree[i].l];
return;
}
long long mid = (tree[i].l + tree[i].r) >> 1;
if(r <= mid) deal(2*i,l,r,f);
else
if(l <= mid) deal(2*i,l,mid,f),deal(2*i+1,mid+1,r,f);
else deal(2*i+1,l,r,f);
if(tree[i].cnt == 0) tree[i].cover = tree[i*2].cover + tree[i*2+1].cover;
else tree[i].cover = width[tree[i].r+1] - width[tree[i].l];
}
int main()
{
cin.sync_with_stdio(false);
cin>>n;
for(int i = 1;i <= n;i++)
{
cin>>a>>b>>h;
xdis[++tot] = a,yline[tot].f = 1,yline[tot].h = 0,yline[tot].l = a,yline[tot].r =b;
xdis[++tot] = b,yline[tot].f = -1,yline[tot].h = h,yline[tot].l = a,yline[tot].r =b;
}
sort(xdis+1,xdis+1+2*n);
sort(yline+1,yline+1+2*n);
xdis[0] = -MAXN;
for(int i = 1;i <= 2*n;i++)
if(xdis[i] != xdis[i-1])
{
f[xdis[i]] = ++num;
width[num] = xdis[i];
}
build(1,1,num-1);
for(int i = 1;i < 2*n;i++)
{
int l = f[yline[i].l],r = f[yline[i].r] - 1;
deal(1,l,r,yline[i].f);
ans += 1ll*tree[1].cover*(yline[i+1].h - yline[i].h);
}
cout<<ans<<endl;
}