题意: 求矩形的并面积。
思路:线段树+离散化+扫描线。
代码:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
struct node
{
int l,r;
node *left,*right;
double len;
int cover;
};
struct line
{
double x;
double y1,y2;
bool type;
} lines[210];
double y[210];
bool operator<(const line& l1,const line& l2)
{
return l1.x<l2.x;
}
node nodes[1000000];
int count1=0;
void buildtree(node* p,int l,int r)
{
p->l=l;p->r=r;p->len=0;p->cover=0;
if(l==r)
return ;
count1++;
p->left=nodes+count1;
count1++;
p->right=nodes+count1;
buildtree(p->left,l,(l+r)/2);
buildtree(p->right,(l+r)/2+1,r);
}
void insert(node* p,int l,int r)
{
if(l==p->l&&r==p->r)
{
p->cover++;p->len=y[r+1]-y[l];return;
}
int mid=(p->l+p->r)/2;
if(r<=mid)
insert(p->left,l,r);
else if(l>mid)
insert(p->right,l,r);
else
insert(p->left,l,mid),insert(p->right,mid+1,r);
if(p->cover==0)
p->len=p->left->len+p->right->len;
}
void delete1(node* p,int l,int r)
{
if(l==p->l&&r==p->r)
{
p->cover--;
if(p->cover==0)
if(l==r)p->len=0;
else p->len=p->left->len+p->right->len;
return ;
}
int mid=(p->l+p->r)/2;
if(r<=mid)
delete1(p->left,l,r);
else if(l>mid)
delete1(p->right,l,r);
else
delete1(p->left,l,mid),delete1(p->right,mid+1,r);
if(p->cover==0)
p->len=p->left->len+p->right->len;
}
int main()
{
int n;int t=0;
while(cin>>n)
{
if(!n)break;
count1=0;t++;
double x1,y1,x2,y2;int c=-1;
for(int i=0;i<n;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
c++;y[c]=y1;lines[c].x=x1,lines[c].y1=y1,lines[c].y2=y2;lines[c].type=1;
c++;y[c]=y2;lines[c].x=x2,lines[c].y1=y1,lines[c].y2=y2;lines[c].type=0;
}
sort(lines,lines+c+1);
sort(y,y+c+1);
int yc=unique(y,y+c+1)-y;
buildtree(nodes,0,yc-1);
double ans=0;
for(int i=0;i<c;i++)
{
int l=lower_bound(y,y+yc,lines[i].y1)-y;
int r=lower_bound(y,y+yc,lines[i].y2)-y;
if(lines[i].type)
insert(nodes,l,r-1);
else
delete1(nodes,l,r-1);
ans+=nodes[0].len*(lines[i+1].x-lines[i].x);
}
printf("Test case #%d\nTotal explored area: %.2f\n\n",t,ans);
}
return 0;
}
题意: 求矩形的并面积。