1645: [Usaco2007 Open]City Horizon 城市地平线
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 616 Solved: 283
[ 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
2 5 1
9 10 4
6 8 2
4 6 3
Sample Output
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
很经典的题,通解是用线段树搞,但是从cqz神犇那里学到一招,排序后用并查集做。
考虑按照矩形的高度由高到低排序,则后面的矩形一定无法覆盖掉前面矩形的部分。
那么我们设f[i]为覆盖了i坐标这点的所有矩形的右边界,则用并查集维护即可。
但注意坐标范围极大,无法一个个扫描坐标计算,所以离散化一下再按照上述思路做。
附代码:
/**************************************************************
Problem: 1645
User: ********
Language: C++
Result: Accepted
Time:636 ms
Memory:11576 kb
****************************************************************/
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<climits>
#include<map>
#include<set>
#define N 40010
using namespace std;
typedef long long ll;
ll n,ip,ans;
struct node{ll l,r,h;}p[N];
bool operator < (node a,node b){return a.h>b.h;}
set<ll>S;
set<ll>::iterator it;
map<ll,ll>M;
map<ll,ll>P;
ll f[N<<1];
ll find(ll x){return x==f[x]?x:f[x]=find(f[x]);}
int main()
{
scanf("%lld",&n);
for(ll i=1;i<=n;i++)
{
scanf("%lld%lld%lld",&p[i].l,&p[i].r,&p[i].h);
S.insert(p[i].l);S.insert(p[i].r);
}
for(it=S.begin();it!=S.end();it++)
M[(*it)]=++ip,P[ip]=(*it);
M[(*it)+1]=++ip,P[ip]=(*it)+1;sort(p+1,p+1+n);
for(ll i=1;i<=ip+1;i++)f[i]=i;
for(ll i=1;i<=n;i++)
{
for(ll j=find(M[p[i].l]);P[j]<p[i].r;j=find(j+1))
{
ll pj1=P[j+1],pj=P[j];
ans+=p[i].h*(pj1-pj);
ll mpr=M[p[i].r];
f[j]=mpr;
}
ll mpr=M[p[i].r];
}printf("%lld\n",ans);
}