/*
这是一道经典题,为啥经典,因为大家都说他是经典题,大家都做他所以说他经典
这是杭电上的一道题(HDU1255),本来上周想训练一下自己线段树由于水平太次,两三道线段树,这一题是看了没做
这周可是花了将近一天的时间,看了几篇博客,才有些眉目
这道题算的是重叠面积,大家应该遇见过这样的情况
给你一个区间,再给你些线段,最后问这个区间上被这些线段覆盖的长度
比如:
给你三条线段
(1,2)(4,5)(3,6)
大家可以有个数组替换这个区间,然后用Y[i]表示i到i+1,1表示覆盖
0,表示未覆盖,这样一一枚举,可以求出被覆盖的长度,但是当给你的
线段是这样的:
(1,1000000),(60000000,70000000),(2000,800000)
1 2 3 4 5 6
这样的话,再用刚才的方法,那就不好了
换下思路:离散化,排序
1 2000 800000 1000000 60000000 70000000
1 2 3 4 5 6
(1,1000000),(60000000,70000000),(2000,800000)
1 4 5 6 2 3
这样的话 再按原来的方法 进行标记,此时我们需要的数组大小为6
L=1000000-1+1+70000000-60000000+1=11000002
到现在我才有离散化的概念
这一题就是离散化加线段树
下面说说我对这道题的理解
线段树的节点包含以下几部分
左右边界l,r此区间被改的次数count,被覆盖一次的长度len,覆盖多次的
长度nlen
每条平行与Y轴直线包括这条线段,x坐标,上下y坐标,还有标记它是前线段
还是后线段的flag;
首先将矩形上所有的Y坐标完全映射到Y坐标上离散化,剔除重复值
建立线段树
存储平行于Y轴的直线
然后检查每条线段,算出面积
面积累加
len()函数是更新一次覆盖的长度
nlen()函数是更新覆盖多次的长度
这是这道题的大概
我是看着别人的程序写的,说抄更为确切
我一直错在Update()函数,最后弄得我不得不
改变以前的写作方式,到现在我都没搞明白自己为啥错的
这道提对我来说,我还需要进一步学习,才能彻悟,人笨没办法
*/
#include<stdio.h>
#include<algorithm>
using namespace std;
#define MAX 1100
typedef struct
{
double x,y1,y2;
__int64 flag;
}LINE;
typedef struct
{
__int64 l,r,count;
double len,nlen;
}NODE;
LINE line[2*MAX];
NODE T[10*MAX];
double Y[2*MAX],tem[2*MAX];
bool comp(LINE a,LINE b)
{
if(a.x<b.x)return true;
if(a.x==b.x&&a.flag<b.flag)return true;
return false;
}
void Build__tree(__int64 i,__int64 l,__int64 r)
{
T[i].l=l;T[i].r=r;
T[i].len=T[i].nlen=0;
T[i].count=0;
if(l+1==r)
return;
__int64 mid;
mid=(l+r)/2;
Build__tree(2*i,l,mid);
Build__tree(2*i+1,mid,r);
}
void Len(__int64 root)
{
if(T[root].count>0)
T[root].len=Y[T[root].r]-Y[T[root].l];
else
T[root].len=T[2*root].len+T[2*root+1].len;
}
void nLen(__int64 root)
{
if(T[root].count>1)
T[root].nlen=Y[T[root].r]-Y[T[root].l];
else if(T[root].count==1)
T[root].nlen=T[root*2].len+T[root*2+1].len;
else
T[root].nlen=T[root*2].nlen+T[root*2+1].nlen;
}
void Update(__int64 root,LINE L)
{
if(L.y1==Y[T[root].l]&&L.y2==Y[T[root].r])
{
T[root].count+=L.flag;
Len(root);
nLen(root);
return ;
}
LINE L1,L2;
if(L.y1>=Y[T[2*root+1].l])
Update(2*root+1,L);
else if(L.y2<=Y[T[2*root].r])
Update(2*root,L);
else
{
L1=L2=L;
L1.y2=Y[T[2*root].r];
L2.y1=Y[T[2*root+1].l];
Update(2*root,L1);
Update(2*root+1,L2);
}
Len(root);
nLen(root);
}
int main()
{
__int64 t,N,i,k;
scanf("%I64d",&t);
while(t--)
{
double x1,x2,y1,y2;
__int64 j;
scanf("%I64d",&N);
for(i=1,k=1;i<=N;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
line[k].x=x1;line[k].y1=y1;line[k].y2=y2;line[k].flag=1;
tem[k++]=y1;
line[k].x=x2;line[k].y1=y1;line[k].y2=y2;line[k].flag=-1;
tem[k++]=y2;
}
sort(line+1,line+2*N+1,comp);
sort(tem+1,tem+2*N+1);
j=1;
Y[1]=tem[1];
for(i=2;i<=2*N;i++)
{
if(tem[i]==tem[i-1])
continue;
Y[++j]=tem[i];
}
Build__tree(1,1,j);
double area=0;
for(i=1;i<=2*N;i++)
{
if(i>1)
area=area+(line[i].x-line[i-1].x)*T[1].nlen;
Update(1,line[i]);
}
printf("%.2lf\n",area);
}
}
我想随着我对这道题的进一步理解,我会进一步完善这篇博客的,因为他值得我进一步去认识!