题目地址:HDOJ地址:HDU 1542 POJ 地址:POJ 1151
第一发扫描线。。费了好大一番功夫。。构思用了半天。。写出来调试成功用了半天。。。真是弱渣。。
所谓扫描线就是从上往下或从下往上扫描,每到一个边,就进行增或删的处理。最后出来的值就是总的面积。对于求面积并的问题,可以参考这篇博客(博客地址),讲的不错。
具体实现过程是用lazy标记此时的边数量,如果大于0,说明这个地方有边,等于0则说明没有边。然后进行更新操作。最后直接使用根节点的值就行。
代码如下:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1
int lazy[10000], cnt;
double sum[10000], c[10000];
struct node
{
double l, r, h;
int f;
} edge[1000];
int cmp(node x, node y)
{
return x.h<y.h;
}
void add(double l, double r, double h, int f)
{
edge[cnt].l=l;
edge[cnt].r=r;
edge[cnt].h=h;
edge[cnt++].f=f;
}
void PushUp(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void update(int ll, int rr, int x, int l, int r, int rt)
{
if(ll<=l&&rr>=r)
{
lazy[rt]+=x;
if(lazy[rt])
{
sum[rt]=c[r+1]-c[l];
}
else if(l!=r)
{
PushUp(rt);
}
else if(l==r)
sum[rt]=0;
return ;
}
int mid=l+r>>1;
if(ll<=mid) update(ll,rr,x,lson);
if(rr>mid) update(ll,rr,x,rson);
if(lazy[rt]==0)
{
PushUp(rt);
}
else
{
sum[rt]=c[r+1]-c[l];
}
}
int erfen(double x, int high)
{
int low=0, mid;
while(low<=high)
{
mid=low+high>>1;
if(c[mid]==x)
return mid;
else if(c[mid]>x)
{
high=mid-1;
}
else
low=mid+1;
}
return -1;
}
int main()
{
int n, i, j, num=0, k;
double x1, x2, y1, y2, ans;
while(scanf("%d",&n)!=EOF&&n)
{
num++;
memset(sum,0,sizeof(sum));
memset(lazy,0,sizeof(lazy));
ans=0;
cnt=0;
k=0;
for(i=0; i<n; i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
c[k++]=x1;
c[k++]=x2;
add(x1,x2,y1,1);
add(x1,x2,y2,-1);
}
sort(edge,edge+2*n,cmp);
sort(c,c+k);
for(i=0; i<2*n-1; i++)
{
int l=erfen(edge[i].l,2*n);
int r=erfen(edge[i].r,2*n);
update(l,r-1,edge[i].f,0,2*n-1,1);
ans+=sum[1]*(edge[i+1].h-edge[i].h);
//printf("%.2lf -- %.2f %.2f\n",ans,sum[1],edge[i+1].h-edge[i].h);
}
printf("Test case #%d\nTotal explored area: %.2lf\n\n",num,ans);
}
return 0;
}