题目地址:http://poj.org/problem?id=1389
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=1000+5;
int y[maxn],nNode;
struct Node{int L,R,mid;int Covered;int Len;Node *pLeft,*pRight;Node(int l=0,int r=0,double len=0,int c=0,Node *pl=NULL,Node *pr=NULL):L(l),R(r),Len(len),Covered(c),pLeft(pl),pRight(pr){ mid=(L+R)/2;}
}tree[maxn*3];
struct Line{int x,y1,y2;bool bLeft;Line(int x=0,int y1=0,int y2=0,bool bl=false):x(x),y1(y1),y2(y2),bLeft(bl){}bool operator < (const Line& l) const {return x<l.x;}
}line[maxn*2];
void BuildTree(Node *root,int s,int e)
{*root=Node(s,e);if(s==e) return;root->pLeft=++nNode+tree;root->pRight=++nNode+tree;BuildTree(root->pLeft,s,root->mid);BuildTree(root->pRight,root->mid+1,e);
}
void Add(Node *root,int s,int e)
{if(root->L==s&&root->R==e) {root->Len=y[e+1]-y[s];root->Covered++;return;}if(e<=root->mid) Add(root->pLeft,s,e);else if(s>=root->mid+1) Add(root->pRight,s,e);else {Add(root->pLeft,s,root->mid);Add(root->pRight,root->mid+1,e);}if(root->Covered==0) root->Len=root->pLeft->Len+root->pRight->Len;
}
void Delete(Node *root,int s,int e)
{if(root->L==s&&root->R==e){root->Covered--;if(root->Covered==0){if(s==e) root->Len=0;else root->Len=root->pLeft->Len+root->pRight->Len;}return;}if(e<=root->mid) Delete(root->pLeft,s,e);else if(s>=root->mid+1) Delete(root->pRight,s,e);else {Delete(root->pLeft,s,root->mid);Delete(root->pRight,root->mid+1,e);}if(root->Covered==0)root->Len=root->pLeft->Len+root->pRight->Len;
}
int main()
{int x1,x2,y1,y2;while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)&&x1!=-1){int nline=0,ycnt=0;y[ycnt++]=y1; y[ycnt++]=y2; line[nline++]=Line(x1,y1,y2,true); line[nline++]=Line(x2,y1,y2,false); while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)&&x1!=-1){y[ycnt++]=y1; y[ycnt++]=y2; line[nline++]=Line(x1,y1,y2,true); line[nline++]=Line(x2,y1,y2,false);}sort(y,y+ycnt); sort(line,line+nline);ycnt=unique(y,y+ycnt)-y;nNode=0; BuildTree(tree,0,ycnt-2);int area=0;for(int i=0;i<nline-1;i++){int L=find(y,y+ycnt,line[i].y1)-y;int R=find(y,y+ycnt,line[i].y2)-y;if(line[i].bLeft) Add(tree,L,R-1);else Delete(tree,L,R-1);area+=(line[i+1].x-line[i].x)*tree[0].Len; }cout<<area<<endl;}return 0;
}