City Horizon
| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 18556 | Accepted: 5115 |
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
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.
【题意】就是矩形面积并。
【解题方法】矩形切割。
【AC 代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 40005;
struct node{
LL x1,y1;
LL x2,y2;
LL sum;
// void read()
// {
// scanf("%I64d%I64d%I64d%I64d",&x1,&y1,&x2,&y2);
// sum=0LL;
// }
}T[maxn];
LL n;
bool cmp(node aa,node bb)
{
if(aa.y2!=bb.y2) return aa.y2<bb.y2;
else{
if(aa.x2!=bb.x2) return aa.x2<bb.x2;
else return aa.x1>bb.x1;
}
}
void Cover(LL x1,LL y1,LL x2,LL y2,LL k,LL c)
{
while(k<n&&(x1>=T[k].x2||x2<=T[k].x1||y1>=T[k].y2||y2<=T[k].y1)) k++;
if(k>=n){
T[c].sum+=(x2-x1)*(y2-y1);
return ;
}
if(x1<T[k].x1){
Cover(x1,y1,T[k].x1,y2,k+1,c);
x1=T[k].x1;
}
if(x2>T[k].x2){
Cover(T[k].x2,y1,x2,y2,k+1,c);
x2=T[k].x2;
}
if(y1<T[k].y1){
Cover(x1,y1,x2,T[k].y1,k+1,c);
y1=T[k].y1;
}
if(y2>T[k].y2){
Cover(x1,T[k].y2,x2,y2,k+1,c);
y2=T[k].y2;
}
}
int main()
{
LL a,b,c;
while(scanf("%I64d",&n)!=EOF)
{
for(int i=0; i<n; i++){
scanf("%I64d%I64d%I64d",&a,&b,&c);
T[i].x1=a,T[i].y1=0LL;
T[i].x2=b,T[i].y2=c;
T[i].sum=0;
}
sort(T,T+n,cmp);
//
//system("pause");
for(LL i=n-1; i>=0; i--){
Cover(T[i].x1,T[i].y1,T[i].x2,T[i].y2,i+1,i);
}
LL ans=0;
for(int i=0; i<n; i++){
ans+=T[i].sum;
}
printf("%I64d\n",ans);
}
return 0;
}
本文介绍了一种通过矩形切割的方法来解决矩形面积并的问题,即计算多个矩形在平面上叠加后的总面积。该问题常见于算法竞赛中,解决思路清晰且附带AC代码。
132

被折叠的 条评论
为什么被折叠?



