您的位置:首页 > 其它

POJ1151-扫面线+线段树+离散化//入门题

2015-08-10 18:13 246 查看
比较水的入门题

记录矩形竖边的x坐标,离散化排序。以被标记的边建树。

扫描线段树,查询线段树内被标记的边。遇到矩形的右边就删除此边

每一段的面积是查询结果乘边的横坐标之差,求和就是答案

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int maxn = 1000;
int N,num,kase;
double savey[maxn*2];

struct line{
double x,y1,y2;
int flag;
bool operator < (const struct line &t) const {return x < t.x;}
}Line[maxn];

struct Node{
int l,r;
double dl,dr;
double len;
int flag;
}SegTree[maxn*4];

void Build(int i,int l,int r)
{
SegTree[i].l = l;
SegTree[i].r = r;
SegTree[i].flag = SegTree[i].len = 0;
SegTree[i].dl = savey[l];
SegTree[i].dr = savey[r];
if(l +1 == r) return;
int mid = (l+r)>>1;
Build(i<<1,l,mid);
Build(i<<1|1,mid,r);
}

void getlen(int t)
{
if(SegTree[t].flag > 0)
{
SegTree[t].len = SegTree[t].dr - SegTree[t].dl;
return ;
}
if(SegTree[t].l+1 == SegTree[t].r) SegTree[t].len = 0;
else SegTree[t].len = SegTree[t<<1].len + SegTree[t<<1|1].len;
}

void Update(int i,line e)
{
if(e.y1 == SegTree[i].dl && e.y2 == SegTree[i].dr)
{
SegTree[i].flag += e.flag;
getlen(i);
return;
}
if(e.y2 <= SegTree[i<<1].dr) Update(i<<1,e);
else if(e.y1 >= SegTree[i<<1|1].dl)    Update(i<<1|1,e);
else
{
line temp = e;
temp.y2 = SegTree[i<<1].dr;
Update(i<<1,temp);
temp = e;
temp.y1 = SegTree[i<<1|1].dl;
Update(i<<1|1,temp);
}
getlen(i);
}

int main()
{
while(~scanf("%d",&N) && N)
{
kase++;
num=1;
double x1,x2,y1,y2;
for(int i=1;i<=N;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
Line[num].x = x1;
Line[num].y1 = y1;
Line[num].y2 = y2;
Line[num].flag = 1;
savey[num++]=y1;
Line[num].x = x2;
Line[num].y1 = y1;
Line[num].y2 = y2;
Line[num].flag = -1;
savey[num++] = y2;
}
sort(Line+1,Line+num);
sort(savey+1,savey+num);
Build(1,1,num-1);
Update(1,Line[1]);
double ans = 0;
for(int i=2;i<num;i++)
{
//printf("%f %f\n",SegTree[1].len,Line[i].x-Line[i-1].x);
ans += SegTree[1].len * (Line[i].x - Line[i-1].x);
Update(1,Line[i]);
}
printf("Test case #%d\n",kase);
printf("Total explored area: %.2f\n\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: