您的位置:首页 > 其它

DOJ - 1005 City Horizon (线段树扫面线)

2016-05-14 15:40 429 查看
问题描述

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)N(1≤N≤40,000)
buildings. Building i's silhouette has a base that spans locations
AiAi
through BiBi
along the horizon (1≤Ai<Bi≤1,000,000,000)(1≤Ai<Bi≤1,000,000,000)
and has height Hi(1≤Hi≤1,000,000,000)Hi(1≤Hi≤1,000,000,000).
Determine the area, in square units, of the aggregate silhouette formed by all
NN
buildings.

输入格式

Line 1: A single integer:
NN

Lines 2→N+12→N+1:
Input line i+1i+1
describes building ii
with three space-separated integers:
AiAi,
BiBi,
and HiHi

输出格式

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

样例输入

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


样例输出

16


数据范围和提示

The first building overlaps with the fourth building for an area of 1 square unit, so the total area is just 31 + 14 + 22 + 23 - 1 = 16.

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#define MAXN 2147483647
using namespace std;
struct line
{
long long f,l,r;
long long h;
friend bool operator < (line a,line b)
{
return a.h < b.h;
}
} yline[80008];
struct Segtree
{
long long l,r,cnt;
long long cover;
} tree[320006];
long long num,tot,n,a,b,h,xdis[80008],width[80008],ans;
unordered_map <long long,long long> f;
void build(long long i,long long l,long long r)
{
tree[i].l = l;
tree[i].r = r;
tree[i].cnt = 0;
if(l == r) return;
long long mid = (l+r)/2;
build(2*i,l,mid);
build(2*i+1,mid+1,r);
}
void deal(long long i,long long l,long long r,long long f)
{
if(l == tree[i].l && r == tree[i].r)
{
tree[i].cnt += f;
if(tree[i].cnt == 0)
{
if(l != r) tree[i].cover = tree[i*2].cover + tree[i*2+1].cover;
else tree[i].cover = 0;
}
else tree[i].cover = width[tree[i].r+1] - width[tree[i].l];
return;
}
long long mid = (tree[i].l + tree[i].r) >> 1;
if(r <= mid) deal(2*i,l,r,f);
else
if(l <= mid) deal(2*i,l,mid,f),deal(2*i+1,mid+1,r,f);
else deal(2*i+1,l,r,f);
if(tree[i].cnt == 0) tree[i].cover = tree[i*2].cover + tree[i*2+1].cover;
else tree[i].cover = width[tree[i].r+1] - width[tree[i].l];
}
int main()
{
cin.sync_with_stdio(false);
cin>>n;
for(int i = 1;i <= n;i++)
{
cin>>a>>b>>h;
xdis[++tot] = a,yline[tot].f = 1,yline[tot].h = 0,yline[tot].l = a,yline[tot].r =b;
xdis[++tot] = b,yline[tot].f = -1,yline[tot].h = h,yline[tot].l = a,yline[tot].r =b;
}
sort(xdis+1,xdis+1+2*n);
sort(yline+1,yline+1+2*n);
xdis[0] = -MAXN;
for(int i = 1;i <= 2*n;i++)
if(xdis[i] != xdis[i-1])
{
f[xdis[i]] = ++num;
width[num] = xdis[i];
}
build(1,1,num-1);
for(int i = 1;i < 2*n;i++)
{
int l = f[yline[i].l],r = f[yline[i].r] - 1;
deal(1,l,r,yline[i].f);
ans += 1ll*tree[1].cover*(yline[i+1].h - yline[i].h);
}
cout<<ans<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: