您的位置:首页 > 其它

HDU 1542 Atlantis

2015-09-05 22:24 267 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1542

题意:给出n个矩形的正对角线的2个端点,求面积并

思路:线段树辅助扫描线求矩形面积并,第一次按照自己思路写这种题目,理解起来不算太困难,倒是写的时候各种奇葩错误。

首先对横坐标进行离散化,因为坐标是浮点数,方便建树以及减少时间消耗,用tsum保存有效长度,因此更新时需要通过二分查找出离散化前的坐标进行更新

将所有的点按照高度排序,每个点依次更新有效线段(是矩形的底线则加1否则减1)并且更新面积,更新的时候当然用的是离散化后的坐标,但是每次右端点都要减1,更新tsum时依然按照没有被减一的右端点更新(这里暂时不是很懂,感觉和线段树的结构有些关系)

扫描线的有效长度是我自己口胡定义出来的,扫描线具体还是画张图理解下



当扫描线走到A的时候,[3,4]加1,有效长度为4和3的横坐标差

当扫描线走到B的时候,[1,2]加1,有效长度加上2和1的横坐标差

当扫描线走到C的时候,[5,6]加1,有效长度加上3和2的横坐标差

当扫描线走到D的时候,[1,2]减1,[1,5]变为0,有效长度减去5和1的横坐标差

当扫描线走到D的时候,[3,4]减1,[6,4]变为0,有效长度减去6和4的横坐标差

只有该区间的值是大于0的时候这个区间表示的线段才是有效线段

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 100030
using namespace std;

struct Tree
{
int l,r,date;
double tsum;
}tree[maxn*3];

struct Node
{
double l,r,h;
int date;
}s[maxn];

int lazy[maxn*3],cnt;
double pos[maxn];

bool cmp(Node p,Node q)
{
return p.h<q.h;
}

void getlen(int root)
{
if (lazy[root]>0)
tree[root].tsum=pos[tree[root].r+1]-pos[tree[root].l];
else if (tree[root].l==tree[root].r)
tree[root].tsum=0;
else tree[root].tsum=tree[root<<1].tsum+tree[root<<1|1].tsum;
}

void build(int root,int l,int r)
{
tree[root].l=l;
tree[root].r=r;
tree[root].tsum=0;
if (l==r) return;

int mid=(l+r)>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
}

void update(int root,int l,int r,int val)
{
if (tree[root].l>=l && tree[root].r<=r)
{
lazy[root]+=val;
getlen(root);
return;
}

int mid=(tree[root].l+tree[root].r)>>1;
if (l<=mid) update(root<<1,l,r,val);
if (r>mid) update(root<<1|1,l,r,val);
getlen(root);
}

void getline(double x1,double x2,double y1,int date)
{
s[cnt].l=x1;
s[cnt].r=x2;
s[cnt].h=y1;
s[cnt].date=date;
cnt++;
}

int main()
{
int n,num,cas=0;
while (scanf("%d",&n)!=EOF && n)
{
cnt=0;
num=0;
memset(lazy,0,sizeof(lazy));
for (int i=0;i<n;i++)
{
double x1,x2,y1,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
getline(x1,x2,y1,1);
getline(x1,x2,y2,-1);
pos[num++]=x1;
pos[num++]=x2;
}

sort(s,s+cnt,cmp);
sort(pos,pos+num);

int tem=1;
for (int i=1;i<num;i++)
{
if (pos[i]!=pos[i-1])
pos[tem++]=pos[i];
}
build(1,0,tem-1);
double res=0;
for (int i=0;i<cnt-1;i++)
{
int l=lower_bound(pos,pos+tem,s[i].l)-pos;
int r=lower_bound(pos,pos+tem,s[i].r)-pos-1;
update(1,l,r,s[i].date);
res+=(s[i+1].h-s[i].h)*tree[1].tsum;
}
printf("Test case #%d\n",++cas);
printf("Total explored area: %.2f\n\n",res);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: