poj3277 City Horizon

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.

分析:
扫描线裸题

在模板中,每一个y值都要记录下来,进行排序离散,然后建立线段树
但是这道题中建筑物又不可能飞在半空中
所以我们可以减少记录的内容

tip

在build的时候
我依旧调用的是(l,mid)和(mid,r)

开ll

这只能说明,hdu的评测机太low,接受不了我的代码
poj上就顺利A了

这里写代码片
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long

using namespace std;

const int N=80010;
int n,tot=0,yi[N];
struct node{
    ll ff,x,ya,yb;
};
node li[N];
struct nd{
    ll ml,mr,s,len;
    int l,r;
};
nd t[N<<2];

int cmp(const node &a,const node &b)
{
    return a.x<b.x;
}

void build(int bh,int l,int r)
{
    t[bh].l=l; t[bh].r=r;
    t[bh].ml=yi[l]; t[bh].mr=yi[r];
    t[bh].s=t[bh].len=0;
    if (t[bh].r-t[bh].l==1) return;
    int mid=(l+r)>>1;
    build(bh<<1,l,mid);
    build(bh<<1|1,mid,r);
}

void update(int bh)
{
    if (t[bh].s>0)
        t[bh].len=t[bh].mr-t[bh].ml;
    else if (t[bh].r-t[bh].l==1)
        t[bh].len=0;
    else t[bh].len=t[bh<<1].len+t[bh<<1|1].len;
    return;
}

void add(int bh,node b)
{
    if (t[bh].ml==b.ya&&t[bh].mr==b.yb)
    {
        t[bh].s+=b.ff;
        update(bh);
        return;
    }
    if (b.yb<=t[bh<<1].mr) add(bh<<1,b);
    else if (b.ya>=t[bh<<1|1].ml) add(bh<<1|1,b);
    else
    {
        node tmp=b;
        tmp.yb=t[bh<<1].mr;
        add(bh<<1,tmp);
        tmp=b;
        tmp.ya=t[bh<<1|1].ml;
        add(bh<<1|1,tmp);
    }
    update(bh);
}

int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        ll u,w,z;
        scanf("%lld%lld%lld",&u,&w,&z);
        tot++; yi[i]=z;
        li[tot].x=u; li[tot].ya=0; li[tot].yb=z; li[tot].ff=1;
        tot++; 
        li[tot].x=w; li[tot].ya=0; li[tot].yb=z; li[tot].ff=-1;
    }
    yi[n+1]=0;
    sort(yi+1,yi+2+n);
    sort(li+1,li+1+tot,cmp);
    build(1,1,n+1);
    add(1,li[1]);
    ll sum=0;
    for (int i=2;i<=tot;i++)
    {
        sum+=t[1].len*(li[i].x-li[i-1].x);
        add(1,li[i]);
    }
    printf("%lld",sum);
    return 0;
}
原文地址:https://www.cnblogs.com/wutongtong3117/p/7673315.html