poj -- 3277City Horizon (线段树)

City HorizonTime Limit: 2000MS Memory Limit: 65536K
Total Submissions: 11351 Accepted: 3026


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

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.


题意:给出N个矩形,每个矩形的坐标在x轴上,矩形之间可能会互相覆盖

求这些矩形所占据的面积和(矩形面积并)。 

 

 

 数据结构:离散化+线段树

 

解法:首先点的坐标太大,所以要离散化,把线段离散化成2个值较小的点

 

线段树用来维护当前线段的有效高度。

 

#include <iostream> #include <algorithm> using namespace std; #define maxn 40005 struct node { int a,b,h; //h是指区间的有效高度,如果[a,b]区间的高度都相同时h才不为0,否则h=0 bool operator<(node t) { return h<t.h; } }Tree[maxn*8],input[maxn]; int sum,n; int hash[maxn*2]; //用于离散化 __int64 ans=0; int Tsearch(int h) { int low=0,high=sum,mid; while (low<=high) { mid=(low+high)>>1; if(hash[mid]==h) return mid; else if(hash[mid]>h) high=mid-1; else low=mid+1; } } void build(int k,int a,int b) { Tree[k].a=a; Tree[k].b=b; Tree[k].h=0; if(b-a>1) { int mid=(a+b)>>1; build(k+k,a,mid); //注意:区间[a,b]是分成[a,mid],[mid,b],是都包含mid的 build(k+k+1,mid,b); } } void add(int k,int a,int b,int h) { if(Tree[k].a==a&&Tree[k].b==b) Tree[k].h=h; else { if(Tree[k].h!=0) //当要更新的区间比本区间窄且搞,把本区间原高度更新到孩子节点上 { Tree[k+k].h=Tree[k+k+1].h=Tree[k].h; //这样可以方便以后的面积计算 Tree[k].h=0; } int mid=(Tree[k].a+Tree[k].b)>>1; //二分深入孩子节点 if(mid<=a) add(k+k+1,a,b,h); else if(mid>=b) add(k+k,a,b,h); else { add(k+k,a,Tree[k+k].b,h); add(k+k+1,Tree[k+k].b,b,h); } } } void cal(int k) { if(Tree[k].h!=0) //h!=0表示这段区间的高度是一样的。计算每个完整的区间 ans+=(__int64)(hash[Tree[k].b]-hash[Tree[k].a])*Tree[k].h; else if(Tree[k].b-Tree[k].a>1) { cal(k+k); cal(k+k+1); } } int main() { int i; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%d%d%d",&input[i].a,&input[i].b,&input[i].h); hash[sum++]=input[i].a; hash[sum++]=input[i].b; } sort(hash,sum+hash); //按x坐标离散化点 //sum=unique(hash,sum+hash)-hash; //这个作用是去除多余的重复的点,可去除(去除后效率更高) build(1,0,sum-1); sort(input,input+n); for (i=0;i<n;i++) add(1,Tsearch(input[i].a),Tsearch(input[i].b),input[i].h); //二分查找离散后的点,用map离散效率低 cal(1); printf("%I64d/n",ans); }  

你可能感兴趣的:(poj -- 3277City Horizon (线段树))