解题思路:线段树求面积并,水题
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1005;
const double eps = 1e-8;
struct Segment
{
int l,r,cover;
double len;
}tree[maxn<<2];
struct Line
{
int val;
double x,y1,y2;
Line(){}
Line(double _x,double _y1,double _y2,int _val)
{
x = _x;
y1 = _y1;
y2 = _y2;
val = _val;
}
};
int n,tmpsize,size;
double edge[maxn],tmp[maxn];
vector<Line> vec;
void build(int rt,int l,int r)
{
tree[rt].l = l, tree[rt].r = r;
tree[rt].cover = tree[rt].len = 0;
if(l + 1 == r) return;
int mid = (l + r) >> 1;
build(rt<<1,l,mid);
build(rt<<1|1,mid,r);
}
void insert(int rt,int l,int r,int val)
{
if(l <= tree[rt].l && tree[rt].r <= r)
{
tree[rt].cover += val;
if(tree[rt].cover == 0)
{
if(tree[rt].l + 1 == tree[rt].r) //叶子节点,没有被覆盖的话长度只能为0
tree[rt].len = 0;
else tree[rt].len = tree[rt<<1].len + tree[rt<<1|1].len;
}
else tree[rt].len = edge[tree[rt].r] - edge[tree[rt].l];
return;
}
int mid = (tree[rt].l + tree[rt].r) >> 1;
if(l < mid) insert(rt<<1,l,r,val);
if(mid < r) insert(rt<<1|1,l,r,val);
if(tree[rt].cover == 0)
tree[rt].len = tree[rt<<1].len + tree[rt<<1|1].len;
else tree[rt].len = edge[tree[rt].r] - edge[tree[rt].l];
}
bool cmp(Line a,Line b)
{
return a.x < b.x;
}
void DiscretData()
{
sort(tmp,tmp+tmpsize);
size = 0;
edge[++size] = tmp[0];
for(int i = 1; i < tmpsize; i++)
if(fabs(tmp[i] - tmp[i-1]) > eps)
edge[++size] = tmp[i];
}
int bisearch(double val)
{
int l = 0, r = size, mid;
while(l <= r)
{
mid = (l + r) >> 1;
if(fabs(edge[mid] - val) < eps) return mid;
else if(edge[mid] - val > eps)
r = mid - 1;
else l = mid + 1;
}
}
int main()
{
int cas = 1;
double x1,y1,x2,y2;
while(scanf("%d",&n),n)
{
tmpsize = 0;
vec.clear();
for(int i = 1; i <= n; i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
vec.push_back(Line(x1,y1,y2,1));
vec.push_back(Line(x2,y1,y2,-1));
tmp[tmpsize++] = y1;
tmp[tmpsize++] = y2;
}
DiscretData();
sort(vec.begin(),vec.end(),cmp);
build(1,1,size);
double ans = 0;
for(int i = 0; i < vec.size(); i++)
{
if(i > 0)
ans += tree[1].len * (vec[i].x - vec[i-1].x);
int l = bisearch(vec[i].y1);
int r = bisearch(vec[i].y2);
insert(1,l,r,vec[i].val);
}
printf("Test case #%d\nTotal explored area: %.2f\n\n",cas++,ans);
}
return 0;
}