题目:http://acm.hdu.edu.cn/showproblem.php?pid=1542
求图形的面积。线段树。仿照别人的思想搞的。http://www.cnblogs.com/ka200812/archive/2011/11/13/2247064.html
下面是AC代码:
#include<cstdio> #include<algorithm> using namespace std; struct line{ double x; double y_up,y_down; int flag; }a[220]; bool cmp(line a,line b){ return a.x<b.x; } double y[220]; struct node{ double y_down,y_up,x; int cover; bool flag; }T[400010]; void build(int id,int l,int r){ T[id].y_down=y[l]; T[id].y_up=y[r]; T[id].flag=false; T[id].x=-1; T[id].cover=0; if(l+1==r){ T[id].flag=true; return ; } int m=(l+r)>>1; build(id<<1,l,m); build(id<<1|1,m,r); } double insert(int id,double x,double l,double r,int flag){ if(r<=T[id].y_down||l>=T[id].y_up) return 0; if(T[id].flag){ //递归到了叶子节点 if(T[id].cover>0){ double temp_x=T[id].x; double ans=(x-temp_x)*(T[id].y_up-T[id].y_down); T[id].x=x; T[id].cover+=flag; return ans; } else{ T[id].cover+=flag; T[id].x=x; return 0; } } double ans1,ans2; ans1=insert(id<<1,x,l,r,flag); ans2=insert(id<<1|1,x,l,r,flag); return ans1+ans2; } int main(){ int n,m; double x1,y1,x2,y2; int ca=0; while(~scanf("%d",&n)){ if(n==0) break; m=0; for(int i=0;i<n;i++){ scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); y[++m]=y1; a[m].x=x1; a[m].y_down=y1; a[m].y_up=y2; a[m].flag=1; y[++m]=y2; a[m].x=x2; a[m].y_down=y1; a[m].y_up=y2; a[m].flag=-1; } sort(y+1,y+m+1); sort(a+1,a+m+1,cmp); build(1,1,m); double ans=0; for(int i=1;i<=m;i++){ ans+=insert(1,a[i].x,a[i].y_down,a[i].y_up,a[i].flag); } printf("Test case #%d\nTotal explored area: %.2f\n\n", ++ca, ans); } return 0; }