覆盖的面积
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5117 Accepted Submission(s): 2568
Problem Description
给定平面上若干矩形,求出被这些矩形覆盖过至少两次的区域的面积.
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
Author
Ignatius.L & weigang Lee
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1540 1828 1823 3016 2871
基础扫描线
#include <cstring>
#include <cstdio>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#define MAX 2005
using namespace std;
int cntline=0;
struct type_line
{
double left,right,y;
int mark;
}line[MAX];
bool cmp(const type_line &a,const type_line &b)
{
return a.y<b.y;
}
vector <double> list;
struct node
{
int left,right,mark;
double sum1,sum2;
}tree[MAX*4];
void addline(double left,double right,double y,int mark)
{
line[cntline].left=left;
line[cntline].right=right;
line[cntline].y=y;
line[cntline].mark=mark;
cntline++;
}
void build(int left,int right,int root)
{
tree[root].left=left;
tree[root].right=right;
tree[root].sum1=tree[root].sum2=0;
tree[root].mark=0;
if(left+1==right)
return;
else
{
int mid=(left+right)/2;
build(left,mid,root*2);
build(mid,right,root*2+1);
}
}
void update(int left,int right,int root,int mark)
{
int l=tree[root].left;
int r=tree[root].right;
if(l>=left&&r<=right)
{
tree[root].mark+=mark;
}
else
{
int mid=(tree[root].left+tree[root].right)/2;
if(left<mid)
update(left,right,root*2,mark);
if(right>mid)
update(left,right,root*2+1,mark);
}
if(tree[root].mark)
{
tree[root].sum1=list[r]-list[l];
}
else if(l+1==r)
tree[root].sum1=0;
else
tree[root].sum1=tree[root*2].sum1+tree[root*2+1].sum1;
if(tree[root].mark>1)
tree[root].sum2=list[r]-list[l];
else if(l+1==r)
tree[root].sum2=0;
else if(tree[root].mark==1)
tree[root].sum2=tree[root*2].sum1+tree[root*2+1].sum1;
else
tree[root].sum2=tree[root*2].sum2+tree[root*2+1].sum2;
}
int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
cntline=0;
list.clear();
double x1,y1,x2,y2;
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
if(x1==x2)
continue;
addline(x1,x2,y1,1);
addline(x1,x2,y2,-1);
list.push_back(x1);
list.push_back(x2);
}
sort(line,line+cntline,cmp);
sort(list.begin(),list.end());
list.erase(unique(list.begin(),list.end()),list.end());
build(0,list.size()-1,1);
double ans=0;
for(int i=0;i<=cntline-1;i++)
{
int left=lower_bound(list.begin(),list.end(),line[i].left)-list.begin();
int right=lower_bound(list.begin(),list.end(),line[i].right)-list.begin();
if(i>0)
ans+=tree[1].sum2*(line[i].y-line[i-1].y);
update(left,right,1,line[i].mark);
}
printf("%.2lf\n",ans);
}
}