覆盖的面积
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6787 Accepted Submission(s): 3449
Problem Description
给定平面上若干矩形,求出被这些矩形覆盖过至少两次的区域的面积.
Input
输入数据的第一行是一个正整数T(1<=T<=100),代表测试数据的数量.每个测试数据的第一行是一个正整数N(1<=N<=1000),代表矩形的数量,然后是N行数据,每一行包含四个浮点数,代表平面上的一个矩形的左上角坐标和右下角坐标,矩形的上下边和X轴平行,左右边和Y轴平行.坐标的范围从0到100000.
注意:本题的输入数据较多,推荐使用scanf读入数据.
注意:本题的输入数据较多,推荐使用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
题意:求面积并
思路:线段树+扫描线
代码:
#include<iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N=4050;
struct node
{
int l,r,c;
double s1,s2;
}t[N<<2];
struct line
{
double l,r,h;
int c;
}ll[N<<2];
bool cmp(line a,line b)
{
return a.h<b.h;
}
int len;
double X[N<<2];
int n;
void build(int x,int l,int r)
{
t[x].l=l;
t[x].r=r;
t[x].c=0;
t[x].s1=0;
t[x].s2=0;
if(l+1==r)return;
int mid=(l+r)/2;
build(x*2,l,mid);
build(x*2+1,mid,r);
}
int find(double x)
{
int l=0;
int r=len;
int mid;
while(l<=r)
{
mid=(l+r)/2;
if(X[mid]==x)
{
return mid;
}
if(X[mid]>x)
{
r=mid-1;
}
else l=mid+1;
}
return l;
}
void add(int x)
{
if(t[x].c>=2)
{
t[x].s2=t[x].s1=X[t[x].r]-X[t[x].l];
}
else if(t[x].c==1)
{
t[x].s1=X[t[x].r]-X[t[x].l];
if(t[x].l+1==t[x].r)t[x].s2=0;
else t[x].s2=t[x*2].s1+t[x*2+1].s1;
}
else
{
if(t[x].l+1==t[x].r)t[x].s1=t[x].s2=0;
else
{
t[x].s1=t[x*2].s1+t[x*2+1].s1;
t[x].s2=t[x*2].s2+t[x*2+1].s2;
}
}
}
void update(int x,int l,int r,int c)
{
if(t[x].l>r||t[x].r<l)
return;
if(t[x].l>=l&&r>=t[x].r)
{
t[x].c+=c;
add(x);
return;
}
update(x*2,l,r,c);
update(x*2+1,l,r,c);
add(x);
}
int main()
{
int T;
cin>>T;
while(T--)
{
scanf("%d",&n);
int i;
int m=0;
double x1,x2,y1,y2;
for(i=0;i<n;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
if(x1>x2)swap(x1,x2);
if(y1>y2)swap(y1,y2);
X[m]=x1;
ll[m].l=x1;
ll[m].r=x2;
ll[m].h=y1;
ll[m++].c=1;
X[m]=x2;
ll[m].l=x1;
ll[m].r=x2;
ll[m].h=y2;
ll[m++].c=-1;
}
sort(X,X+m);
len=1;
for(i=1;i<m;i++)
{
if(X[i-1]!=X[i])
X[len++]=X[i];
}
sort(ll,ll+m,cmp);
len--;
build(1,0,len);
double ans=0;
for(i=0;i<m-1;i++)
{
int x=find(ll[i].l);
int y=find(ll[i].r);
update(1,x,y,ll[i].c);
ans+=t[1].s2*(ll[i+1].h-ll[i].h);
}
printf("%.2lf\n",ans);
}
return 0;
}