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 Ai through Bi along the horizon (1 ≤ Ai < Bi ≤ 1,000,000,000) and has height Hi (1 ≤ Hi ≤ 1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by all N buildings.
Input
Line 1: A single integer:
N
Lines 2.. N+1: Input line i+1 describes building i with three space-separated integers: Ai, Bi, and Hi
Lines 2.. N+1: Input line i+1 describes building i with three space-separated integers: Ai, Bi, and Hi
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
Hint
The first building overlaps with the fourth building for an area of 1 square unit, so the total area is just 3*1 + 1*4 + 2*2 + 2*3 - 1 = 16.
题目大意:在水平直线上给定一组矩形,这些矩形的底边在同一水平线上,求这些矩形占据的面积。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
const int maxn=40010;
using namespace std;
struct node{
int l,r;
int high;
node(){
l=0;r=0;high=0;
}
}tree[maxn*8];
int seg[maxn*4],a[maxn*2],b[maxn*2],height[maxn*2];
void create_tree(int h,int x,int y){
tree[h].l=x;tree[h].r=y;
tree[h].high=0;
if(x+1==y)return;
int mid=(x+y)/2;
create_tree(h*2,x,mid);
create_tree(h*2+1,mid,y);
}
void update(int id,int x,int y,int h){
if(seg[tree[h].l]==x && seg[tree[h].r]==y){
if(tree[h].high<height[id])
tree[h].high=height[id];
return ;
}
int mid=seg[(tree[h].l+tree[h].r)/2];
if(y<=mid)
update(id,x,y,h*2);
else if(x>=mid)
update(id,x,y,h*2+1);
else{
update(id,x,mid,h*2);
update(id,mid,y,h*2+1);
}
}
long long sum(int high,int h){
if(tree[h].high<high)
tree[h].high=high;
if(tree[h].l+1==tree[h].r)
return (long long)(seg[tree[h].r]-seg[tree[h].l])*tree[h].high;
long long a=sum(tree[h].high,h*2);
long long b=sum(tree[h].high,h*2+1);
return a+b;
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
int k=0;
for(int i=1;i<=n;i++){
scanf("%d%d%d",&a[i],&b[i],&height[i]);
seg[++k]=a[i];
seg[++k]=b[i];
}
sort(seg+1,seg+k+1);
int len=unique(seg+1,seg+k+1)-(seg+1);
create_tree(1,1,len);
for(int i=1;i<=len;i++)
update(i,a[i],b[i],1);
long long ans=sum(0,1);
printf("%lld\n",ans);
}
return 0;
}