# 【bzoj1645】[Usaco2007 Open]City Horizon 城市地平线 离散化+线段树

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个矩形块，交求面积并.

* 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

* Line 1: The total area, in square units, of the silhouettes formed by all N buildings

4
2 5 1
9 10 4
6 8 2
4 6 3

16

#include <cstdio>
#include <algorithm>
#define lson l , mid , x << 1
#define rson mid , r , x << 1 | 1        //not "mid+1,r,x<<1|1"
#define N 40001
using namespace std;
struct data
{
long long a , b , h;
int left , right;
}k[N];
struct pt
{
long long num;
int from;
}p[N << 1];
long long sum[N << 3] , tag[N << 3] , pos[N << 1];
int tot;
bool cmp1(pt a , pt b)
{
return a.num < b.num;
}
bool cmp2(data a , data b)
{
return a.h < b.h;
}
void pushup(int x)
{
sum[x] = sum[x << 1] + sum[x << 1 | 1];
}
void pushdown(int l , int r , int x)
{
if(tag[x])
{
int mid = (l + r) >> 1;
sum[x << 1] = tag[x] * (pos[mid] - pos[l]);
sum[x << 1 | 1] = tag[x] * (pos[r] - pos[mid]);        //not "pos[mid+1]"
tag[x << 1] =  tag[x << 1 | 1] = tag[x];
tag[x] = 0;
}
}
void update(int b , int e , long long a , int l , int r , int x)
{
if(b <= l && r <= e)
{
sum[x] = a * (pos[r] - pos[l]);
tag[x] = a;
return;
}
pushdown(l , r , x);
int mid = (l + r) >> 1;
if(b < mid) update(b , e , a , lson);        //not "b<=mid"
if(e > mid) update(b , e , a , rson);
pushup(x);
}
int main()
{
int n , i , rnd = 0;
scanf("%d" , &n);
for(i = 0 ; i < n ; i ++ )
{
scanf("%lld%lld%lld" , &k[i].a , &k[i].b , &k[i].h);
p[tot].num = k[i].a;
p[tot ++ ].from = i;
p[tot].num = k[i].b;
p[tot ++ ].from = i;
}
sort(p , p + tot , cmp1);
for(i = 0 ; i < tot ; i ++ )
{
if(i == 0 || p[i].num != p[i - 1].num)
rnd ++ ;
if(k[p[i].from].a == p[i].num) k[p[i].from].left = rnd;
if(k[p[i].from].b == p[i].num) k[p[i].from].right = rnd;
pos[rnd] = p[i].num;
}
sort(k , k + n , cmp2);
for(i = 0 ; i < n ; i ++ )
update(k[i].left , k[i].right , k[i].h , 1 , rnd , 1);
printf("%lld\n" , sum[1]);
return 0;
}
posted @ 2017-01-13 10:26  GXZlegend  阅读(328)  评论(0编辑  收藏  举报