链接:http://acm.hdu.edu.cn/showproblem.php?pid=1542
刚刚学会的矩形面积并,从下往上扫描,对x坐标离散化,在离散化后的x坐标上建立线段树,对于每条线段,二分找到左右端点,然后不断更新线段并统计面积
代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<vector> using namespace std; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 const int MAXN=1010; struct line{ double h,l,r; int f; line(){} line(double a,double b,double c,int d):h(a),l(b),r(c),f(d){} }seg[MAXN]; struct Tree{ double len; int cover; }sum[MAXN*3]; double xs[MAXN]; int linecnt,xcnt; inline bool cmp(line a,line b){ return a.h<b.h; } void addline(double x1,double y1,double x2,double y2){ xs[++linecnt]=x1;seg[linecnt]=line(y1,x1,x2,1); xs[++linecnt]=x2;seg[linecnt]=line(y2,x1,x2,-1); } int Search(double k,int l,int r){ while(l<=r){ int m=(l+r)>>1; if(xs[m]==k)return m; if(xs[m]>k)r=m-1; else l=m+1; } return l; } inline void pushup(int rt,int l,int r){ if(sum[rt].cover)sum[rt].len=xs[r+1]-xs[l]; else if(l==r)sum[rt].len=0; else sum[rt].len=sum[rt<<1].len+sum[rt<<1|1].len; } void update(int L,int R,int c,int l,int r,int rt){ if(L<=l&&r<=R){ sum[rt].cover+=c; pushup(rt,l,r); return; } int m=(l+r)>>1; if(L<=m)update(L,R,c,lson); if(R>m)update(L,R,c,rson); pushup(rt,l,r); } int main(){ // freopen("D://input.txt","r",stdin); int n,kase=1; while(scanf("%d",&n)!=EOF&&n){ printf("Test case #%d\nTotal explored area: ",kase++); linecnt=xcnt=0;int i; while(n--){ double xx[2],yy[2]; scanf("%lf%lf%lf%lf",&xx[0],&yy[0],&xx[1],&yy[1]); addline(xx[0],yy[0],xx[1],yy[1]); } sort(seg+1,seg+linecnt+1,cmp);sort(xs+1,xs+linecnt+1); memset(sum,0,sizeof(sum)); for(i=1;i<=linecnt;i++){ if(xs[i+1]!=xs[i]) xs[++xcnt]=xs[i]; } double area=0; for(i=1;i<linecnt;i++){ int L=Search(seg[i].l,1,xcnt),R=Search(seg[i].r,1,xcnt)-1; if(L<=R){ update(L,R,seg[i].f,1,xcnt,1); area+=sum[1].len*(seg[i+1].h-seg[i].h); } } printf("%.2f\n\n",area); } return 0; }