Topic Link: Click to open the link
Title Description: Given some rectangles, the total area of these rectangles, if there is overlap, only one time
Thinking: Scan line + line tree + discrete (code scan from top to bottom)
Code:
#include <cstdio> #include <algorithm> #define MAXN 110#define LL ((rt<<1) +1) #define RR (rt<<1) +2) using namespace Std;int n;struct segment{double l,r,h; int F; BOOL operator< (const segment& B) const{return h>b.h; }}SG[2*MAXN];d ouble pos[2*maxn];int id;void addsegment (double x1,double y1,double x2,double y2) {sg[id].l=x1;sg[id].r= X2; sg[id].h=y1;sg[id].f=1; pos[id++]=x1; sg[id].l=x1;sg[id].r=x2; Sg[id].h=y2;sg[id].f=-1; POS[ID++]=X2;} int binary (double key,int low,int high) {while (low<=high) {int mid= (Low+high)/2; if (Pos[mid]==key) return mid; else if (Key<pos[mid]) high=mid-1; else low=mid+1; } return-1;} struct tree{int l,r; int cover; Double Len;} tree[8*maxn];void Build (int rt,int l,int r) {tree[rt].l=l; Tree[rt].r=r; tree[rt].cover=0; tree[rt].len=0; if (l==r-1) return; int mid= (L+R) >>1; Build (Ll,l,mid); Build (Rr,mid,r);} void pushup (int rt) {if (tree[rt].cover) TREE[RT].LEN=POS[TREE[RT].R]-POS[TREE[RT].L]; else if (tree[rt].l==tree[rt].r-1) tree[rt].len=0; else Tree[rt].len=tree[ll].len+tree[rr].len;} void update (int rt,int l,int r,int f) {if (tree[rt].l==l&&tree[rt].r==r) {tree[rt].cover+=f; Pushup (RT); Return } int mid= (TREE[RT].L+TREE[RT].R) >>1; if (r<=mid) update (LL,L,R,F); else if (l>=mid) update (RR,L,R,F); else{Update (LL,L,MID,F); Update (RR,MID,R,F); } pushup (RT);} int main () {int case=0; while (scanf ("%d", &n)!=eof&&n!=0) {id=0; Double x1,y1,x2,y2; for (int i=0;i<n;++i) {scanf ("%lf%lf%lf%lf", &x1,&y1,&x2,&y2); Addsegment (X1,Y1,X2,Y2); } n= (n<<1); Sort (sg,sg+n); Sort (pos,pos+n); int m=1; for (int i=1;i<n;++i) if (pos[i]!=POS[I-1]) pos[m++]=pos[i]; Build (0,0,m-1); Double ans=0; int l=binary (SG[0].L,0,M-1); int r=binary (SG[0].R,0,M-1); Update (0,L,R,SG[0].F); for (int i=1;i<n;i++) {ans+= (sg[i-1].h-sg[i].h) *tree[0].len; L=binary (sg[i].l,0,m-1); R=binary (sg[i].r,0,m-1); Update (0,L,R,SG[I].F); } printf ("Test case #%d\n", ++case); printf ("Total explored area:%.2f\n\n", ans); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
hdu1542 Atlantis (scan line + segment tree + discrete) rectangular intersection area