POJ 3277 City Horizon 矩形切割

来源:互联网 发布:干湿报警阀组的算法 编辑:程序博客网 时间:2024/06/06 01:17

City Horizon
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 18556 Accepted: 5115

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. Buildingi's silhouette has a base that spans locations Ai throughBi along the horizon (1 ≤ Ai < Bi ≤ 1,000,000,000) and has heightHi (1 ≤ Hi ≤ 1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by allN 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 allN buildings

Sample Input

42 5 19 10 46 8 24 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.

【题意】就是矩形面积并。

【解题方法】矩形切割。

【AC 代码】

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 40005;struct node{    LL x1,y1;    LL x2,y2;    LL sum;//    void read()//    {//        scanf("%I64d%I64d%I64d%I64d",&x1,&y1,&x2,&y2);//        sum=0LL;//    }}T[maxn];LL n;bool cmp(node aa,node bb){    if(aa.y2!=bb.y2) return aa.y2<bb.y2;    else{        if(aa.x2!=bb.x2) return aa.x2<bb.x2;        else             return aa.x1>bb.x1;    }}void Cover(LL x1,LL y1,LL x2,LL y2,LL k,LL c){    while(k<n&&(x1>=T[k].x2||x2<=T[k].x1||y1>=T[k].y2||y2<=T[k].y1)) k++;    if(k>=n){        T[c].sum+=(x2-x1)*(y2-y1);        return ;    }    if(x1<T[k].x1){        Cover(x1,y1,T[k].x1,y2,k+1,c);        x1=T[k].x1;    }    if(x2>T[k].x2){        Cover(T[k].x2,y1,x2,y2,k+1,c);        x2=T[k].x2;    }    if(y1<T[k].y1){        Cover(x1,y1,x2,T[k].y1,k+1,c);        y1=T[k].y1;    }    if(y2>T[k].y2){        Cover(x1,T[k].y2,x2,y2,k+1,c);        y2=T[k].y2;    }}int main(){    LL a,b,c;    while(scanf("%I64d",&n)!=EOF)    {        for(int i=0; i<n; i++){            scanf("%I64d%I64d%I64d",&a,&b,&c);            T[i].x1=a,T[i].y1=0LL;            T[i].x2=b,T[i].y2=c;            T[i].sum=0;        }        sort(T,T+n,cmp);        //        //system("pause");        for(LL i=n-1; i>=0; i--){            Cover(T[i].x1,T[i].y1,T[i].x2,T[i].y2,i+1,i);        }        LL ans=0;        for(int i=0; i<n; i++){            ans+=T[i].sum;        }        printf("%I64d\n",ans);    }    return 0;}


0 0
原创粉丝点击