【hdu1828/poj1177】线段树求矩形周长并

时间:2023-03-08 20:39:54

题意如图

【hdu1828/poj1177】线段树求矩形周长并

【hdu1828/poj1177】线段树求矩形周长并

题解:这题非常类似与矩形面积并,也是维护一个被覆盖了一次以上的线段总长。

但是周长要算新出现的,所以每次都要和上一次做差求绝对值。

x轴做一遍,y轴做一遍。

但是有个问题:矩形边界重合的时候的处理。举个例子,在处理x轴的时候:

【hdu1828/poj1177】线段树求矩形周长并

怎么处理呢?我们在对y排序的时候把下边界(下边界+1,上边界-1)排在上边界前面,这样做就不会重复算了。

 #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std; typedef long long LL;
const int N=*,INF=(int)1e9;
struct node{
int x1,x2,y,d;
}a[N];
struct point{
int x,y;LL d;
}p[N];
struct trnode{
int l,r,lc,rc,cnt;
LL rl,len;
}t[*N];
int n,mx,pl,al,tl,z[N][];
LL num[N]; bool cmp_d(point x,point y){return x.d<y.d;}
bool cmp_y(node x,node y)
{
if(x.y==y.y) return x.d>y.d;//处理重边
else return x.y<y.y;
}
void inp(int x,int y,int d){p[++pl].x=x;p[pl].y=y;p[pl].d=d;}
void ina(int x1,int x2,int y,int d){a[++al].x1=x1;a[al].x2=x2;a[al].y=y;a[al].d=d;}
int myabs(int x){return x> ? x:-x;}
int maxx(int x,int y){return x>y ? x:y;} void unique()
{
int now=;p[].d=INF;
sort(p+,p++pl,cmp_d);
for(int i=;i<=pl;i++)
{
if(p[i].d!=p[i-].d) now++,num[now]=(LL)p[i].d;
z[p[i].x][p[i].y]=now;
}
mx=now;
} void make_edge()
{
al=;mx=;
for(int i=;i<=n;i++)
{
if(z[i][]>z[i][]) swap(z[i][],z[i][]);
if(z[i][]>z[i][]) swap(z[i][],z[i][]);
ina(z[i][],z[i][],z[i][],);
ina(z[i][],z[i][],z[i][],-);
mx=maxx(mx,z[i][]);
}
// ina(1,mx-1,INF,-1);
} int bt(int l,int r)
{
int x=++tl;
t[x].l=l;t[x].r=r;
t[x].lc=t[x].rc=;
t[x].cnt=;t[x].len=;
t[x].rl=num[r+]-num[l];
if(l<r)
{
int mid=(l+r)/;
t[x].lc=bt(l,mid);
t[x].rc=bt(mid+,r);
}
return x;
} void upd(int x)
{
int lc=t[x].lc,rc=t[x].rc;
if(t[x].cnt>=) t[x].len=t[x].rl;
else t[x].len=t[lc].len+t[rc].len;
} void change(int x,int l,int r,int d)
{
if(t[x].l==l && t[x].r==r)
{
t[x].cnt+=d;
upd(x);
return;
}
int lc=t[x].lc,rc=t[x].rc,mid=(t[x].l+t[x].r)/;
if(r<=mid) change(lc,l,r,d);
else if(l>mid) change(rc,l,r,d);
else
{
change(lc,l,mid,d);
change(rc,mid+,r,d);
}
upd(x);
} void output()
{
for(int i=;i<=tl;i++)
printf("l = %d r = %d cnt = %d len = %lf rl = %lf \n",t[i].l,t[i].r,t[i].cnt,t[i].len,t[i].rl);
} int main()
{
freopen("a.in","r",stdin);
while(scanf("%d",&n)!=EOF)
{
LL pre,ans,now;ans=;pl=;
for(int i=;i<=n;i++)
{
for(int j=;j<=;j++)
{
scanf("%d",&z[i][j]);
inp(i,j,z[i][j]);
}
}
unique();
for(int k=;k<=;k++)
{
if(k==)
{
for(int i=;i<=n;i++) swap(z[i][],z[i][]),swap(z[i][],z[i][]);
}
make_edge();
sort(a+,a++al,cmp_y);
tl=;bt(,mx-);
pre=;
for(int i=;i<=al;i++)
{
change(,a[i].x1,a[i].x2-,a[i].d);
now=t[].len;
ans+=myabs(now-pre);
pre=now;
}
// printf("ans = %d\n",ans);
}
printf("%lld\n",ans);
}
return ;
}