问题描述
给定平面上若干矩形,求出被这些矩形覆盖过至少两次的区域的面积.
Input
输入数据的第一行是一个正整数T(1<=T<=100),代表测试数据的数量.每个测试数据的第一行是一个正整数N(1<=N<=1000),代表矩形的数量,然后是N行数据,每一行包含四个浮点数,代表平面上的一个矩形的左上角坐标和右下角坐标,矩形的上下边和X轴平行,左右边和Y轴平行.坐标的范围从0到100000.
注意:本题的输入数据较多,推荐使用scanf读入数据.
Output
对于每组测试数据,请计算出被这些矩形覆盖过至少两次的区域的面积.结果保留两位小数.
Sample Input
2
5
1 1 4 2
1 3 3 7
2 1.5 5 4.5
3.5 1.25 7.5 4
6 3 10 7
3
0 0 1 1
1 0 2 1
2 0 3 1
Sample Output
7.63
0.00
分析:
类似求矩形面积并
但是这次是要求覆盖两次及以上的面积.
同时维护区间被覆盖一次的长度和覆盖两次的长度len1和len2
如果cnt>=2则区间被全覆盖至少两次,len2可以直接算出来
如果cnt=1,表明当前区间被全覆盖一次,pushup的目的是更新还未更新的信息,这时候子区间的len1应该多被覆盖了一次就变成len2了
所以当前区间覆盖两次的长度len2为两个子区间的len1之和
如果cnt=0,则len2等于两个子区间的len2之和
code:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
typedef long long ll;
const int inf=0x3f3f3f3f;
const int inn=0x80808080;
using namespace std;
const int maxm=1e5+5;
struct line{
double l,r,h;
int f;
line(){};
line(double ll,double rr,double hh,int ff){
l=ll,r=rr,h=hh,f=ff;
}
}e[maxm<<2];
bool cmp(line a,line b){
return a.h<b.h;
}
struct Node{
int cnt;
double len,len2;
}a[maxm<<2];
double x[maxm<<2];
void pushup(int l,int r,int node){
if(a[node].cnt){//更新单次覆盖
a[node].len=x[r+1]-x[l];
}else if(l==r){
a[node].len=0;
}else{
a[node].len=a[node*2].len+a[node*2+1].len;
}
//
if(a[node].cnt>=2){//更新多次覆盖
a[node].len2=x[r+1]-x[l];
}else if(l==r){
a[node].len2=0;
}else if(a[node].cnt==1){
a[node].len2=a[node*2].len+a[node*2+1].len;
}else{
a[node].len2=a[node*2].len2+a[node*2+1].len2;
}
}
void update(int st,int ed,int l,int r,int node,int val){
if(st<=l&&ed>=r){
a[node].cnt+=val;
pushup(l,r,node);
return ;
}
int mid=(l+r)/2;
if(st<=mid)update(st,ed,l,mid,node*2,val);
if(ed>=mid+1)update(st,ed,mid+1,r,node*2+1,val);
pushup(l,r,node);
}
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
int cnt=0;
for(int i=0;i<n;i++){
double x1,x2,y1,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
x[cnt]=x1;
e[cnt++]=line(x1,x2,y1,1);
x[cnt]=x2;
e[cnt++]=line(x1,x2,y2,-1);
}
sort(x,x+cnt);
sort(e,e+cnt,cmp);
int m=unique(x,x+cnt)-x;
double ans=0;
for(int i=0;i<cnt;i++){
int l=lower_bound(x,x+m,e[i].l)-x;
int r=lower_bound(x,x+m,e[i].r)-x-1;
update(l,r,0,m-1,1,e[i].f);
ans+=a[1].len2*(e[i+1].h-e[i].h);
}
printf("%.2f\n",ans);
}
return 0;
}