题目
给出一些可能重叠的矩形,求矩形的面积
分析
其实这道题用离散+朴素 O ( n 2 ) O(n^2) O(n2)慢不了多少,但是为了推行线段树 O ( n l o g n ) O(nlogn) O(nlogn)的方法,只是随便搞搞,用扫描线维护横坐标,并用线段树进行纵坐标的区间修改
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
struct rec{double x,yy1,yy2; bool flag;}a[201];
int n,ccnt; double mark[801],w[801],uniq[201];
bool cmp(rec a,rec b){return a.x<b.x;}
void update(int k,int l,int r,int x,int y,bool end){
if (l==x&&r==y){
mark[k]+=end?1:-1;
if (mark[k]) w[k]=uniq[r+1]-uniq[l];//标记永久化
else if (l==r) w[k]=0;
else w[k]=w[k<<1]+w[k<<1|1];
return;
}
int mid=(l+r)>>1;
if (y<=mid) update(k<<1,l,mid,x,y,end);
else if (x>mid) update(k<<1|1,mid+1,r,x,y,end);
else update(k<<1,l,mid,x,mid,end),update(k<<1|1,mid+1,r,mid+1,y,end);
if (mark[k]) w[k]=uniq[r+1]-uniq[l];
else if (l==r) w[k]=0;
else w[k]=w[k<<1]+w[k<<1|1];
}
int main(){
while (scanf("%d",&n)==1&&n){
int cnt=0,m=0; memset(w,0,sizeof(w)); memset(mark,0,sizeof(mark));
for (register int i=1;i<=n;i++){
double xx1,xx2,yy1,yy2;
scanf("%lf%lf%lf%lf",&xx1,&yy1,&xx2,&yy2);
a[++cnt]=(rec){xx1,yy1,yy2,1}; uniq[++m]=yy1;
a[++cnt]=(rec){xx2,yy1,yy2,0}; uniq[++m]=yy2;
}
std::stable_sort(uniq+1,uniq+1+m);
m=std::unique(uniq+1,uniq+1+m)-(uniq+1);//离散
std::stable_sort(a+1,a+1+cnt,cmp);
double ans=0;
for (register int i=1;i<cnt;i++){
int x=std::lower_bound(uniq+1,uniq+1+m,a[i].yy1)-uniq;//二分
int y=std::lower_bound(uniq+1,uniq+1+m,a[i].yy2)-uniq-1;
update(1,1,m,x,y,a[i].flag);
ans+=w[1]*(a[i+1].x-a[i].x);//求答案
}
printf("Test case #%d\n",++ccnt);
printf("Total explored area: %.2lf\n\n",ans);
}
return 0;
}