poj 1389 线段树求面积并 整数版本

来源:互联网 发布:淘宝下架日是什么意思 编辑:程序博客网 时间:2024/05/15 13:40

一个小bug搞了半天,由于没有离散化,线段树的域的空间应该是4*maxn,maxn为x坐标的最大值

View Code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn = 50000; //maxn 为 x 的最大值(如果离散化了就是矩形的个数*2)
int sum[maxn<<2];
int cover[maxn<<2];
struct seg{
int l,r,h;
int flag;
seg(){}
seg(int _l,int _r,int _h,int _flag):l(_l),r(_r),h(_h),flag(_flag){}
bool operator <(const seg &cmp) const {
return h<cmp.h;
}
}horizontal_seg[maxn];
void pushup(int rt,int m){
if(cover[rt]){
sum[rt]=m;
}
else if(m==1){
sum[rt]=0;
}
else sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void update(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
cover[rt]+=c;
pushup(rt,r-l+1);
return ;
}
int m=(l+r)>>1;
if(L<=m) update(L,R,c,lson);
if(R>m) update(L,R,c,rson);
pushup(rt,r-l+1);
}
int main(){
int n,i,tot;
int x1,y1,x2,y2;
while(1){
tot=n=0;
int mx=0;
while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2),x1!=-1) {
if(x2>mx) mx=x2;
n++;
horizontal_seg[tot++]=seg(x1,x2,y1,1);
horizontal_seg[tot++]=seg(x1,x2,y2,-1);
}
if(n==0) break;
sort(horizontal_seg,horizontal_seg+tot);
memset(cover , 0 , sizeof(cover));
memset(sum , 0 , sizeof(sum));
int area=0;
for(i=0;i<tot-1;i++){
int left=horizontal_seg[i].l;
int right=horizontal_seg[i].r-1;
update(left,right,horizontal_seg[i].flag,0,50000,1);
area+=sum[1]*(horizontal_seg[i+1].h-horizontal_seg[i].h);
}
printf("%d\n",area);
}
return 0;
}



原创粉丝点击