定义: 有若干个边平行于坐标轴的矩形,问他们覆盖的面积总和。
扫描线算法: 选取一个坐标轴平行于扫描线(图中是x轴),每次扫描线移动到矩形起始边,就标记相应的范围+1,移到终止边时就-1。每次移动到新边时,计算这次和上次扫描线的间距d,新加的面积就是 已覆盖的长度*d。已覆盖面积可用线段树统计。
例题:HDU - 1542
#include<bits/stdc++.h>
#define ll long long
#define lf double
#define IOS std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define Rep(i,l,r) for(int i=(l);i<=(r);i++)
using namespace std;
#define MAXN 1000
struct Edge{double x,y1,y2;int type;};
bool cmp(Edge x,Edge y){return x.x<y.x;}
double Y[MAXN+5];
struct Tree{
//z统计当前节点管理的能覆盖的长度,根节点就是统计的总覆盖长度
double l,r,z;int cover;Tree *left,*right;
Tree(int l,int r):l(Y[l]),r(Y[r]),cover(0),z(0){
if(r-l>1)left=new Tree(l,l+r>>1),right=new Tree(l+r>>1,r);
else left=right=NULL;
}
void pushup(){
if(cover)z=r-l;else if(!left)z=0;
else z=left->z+right->z;
}
void change(double x,double y,int z)
{
if(l==x&&r==y){cover+=z;pushup();return;}
if(y<=left->r)left->change(x,y,z);
else if(x>=right->l)right->change(x,y,z);
else left->change(x,left->r,z),right->change(right->l,y,z);
pushup();
}
};
int n;
Tree* root;
Edge a[MAXN+5];
double ans=0;
int main()
{
int cntt=0;
while(cin>>n)
{
cntt++;if(!n)break;
int t=0;
Rep(i,1,n){
double x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
//扫描线平行于y轴
a[++t]=(Edge){x1,y1,y2,1}; Y[t]=y1;
a[++t]=(Edge){x2,y1,y2,-1}; Y[t]=y2;
}
sort(a+1,a+1+t,cmp);sort(Y+1,Y+1+t);
int t2=unique(Y+1,Y+1+t)-(Y+1);//离散化
root=new Tree(1,t2);ans=0;
for(int i=1;i<=t;i++){
ans+=(a[i].x-a[i-1].x)*root->z;
root->change(a[i].y1,a[i].y2,a[i].type);
}
printf("Test case #%d\nTotal explored area: %.2lf\n\n",cntt,ans);
}
return 0;
}