bzoj 1645: [Usaco2007 Open]City Horizon 城市地平线(离散化+扫描线)

1645: [Usaco2007 Open]City Horizon 城市地平线

Time Limit: 5 Sec   Memory Limit: 64 MB
Submit: 541   Solved: 255
[ Submit][ Status][ Discuss]

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 3*1 + 1*4 + 2*2 + 2*3 - 1 = 16.

HINT

Source

[ Submit][ Status][ Discuss]


题解:扫描线+线段树

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 200000
#define LL long long
using namespace std;
int  n,m;
LL len[N*4],h[N],ans;
int a[N],b[N],v[N],cnt,num[N],tot,tree[N*4];
struct data 
{
    int l,r,x,pd;
}c[N];
int cmp(int x,int y)
{
    return h[x]<h[y];
}
int cmp1(data a,data b)
{
    return a.x<b.x;
}
void update(int now,int l,int r)
{
    if (tree[now]>0)
     len[now]=(LL)(v[r]-v[l-1]);
    else if (l==r)  len[now]=0;
    else len[now]=len[now<<1]+len[now<<1|1];
}
void qjchange(int now,int l,int r,int ll,int rr,int v)
{
    if (l>=ll&&r<=rr)
    {
        tree[now]+=v;
        update(now,l,r);
        return;
    }
    int mid=(l+r)/2;
    if (ll<=mid)  qjchange(now<<1,l,mid,ll,rr,v);
    if (rr>mid)  qjchange(now<<1|1,mid+1,r,ll,rr,v);
    update(now,l,r);
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        int x,y; scanf("%d%d",&x,&y);
        ++tot;  c[tot].l=1; c[tot].x=x; c[tot].pd=1;
        ++tot;  c[tot].l=1; c[tot].x=y; c[tot].pd=-1;
        scanf("%lld",&h[i]); b[i]=i;
    }
    b[n+1]=n+1; h[n+1]=1;
    b[n+2]=n+2; h[n+2]=0;
    sort(b+1,b+n+3,cmp);
    h[b[0]]=1000000001;
    for (int i=1;i<=n+2;i++)
     if (h[b[i]]!=h[b[i-1]])
      ++cnt,v[cnt]=h[b[i]],num[b[i]]=cnt;
     else num[b[i]]=cnt;
    for (int i=1;i<=2*n;i++)
      c[i].r=num[(i-1)/2+1],c[i].l=num[n+1];
    sort(c+1,c+2*n+1,cmp1);
    for (int i=1;i<=2*n;i++)
    {
        if (i!=1)  ans+=(LL)(c[i].x-c[i-1].x)*len[1];
        qjchange(1,1,cnt,c[i].l,c[i].r,c[i].pd);
    }
    printf("%lld\n",ans);
}



相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页