跟着13哥学线段树。
详情请见上一篇转载的博客。
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
#define N 210
struct Line
{
double x1,x2,y;
int cov;
}l[N];
bool cmp(Line i,Line j)
{
return i.y<j.y;
}
double x[N],x1,x2,y,y2;
int n;
map<double,int>m;
struct node
{
int l,r,cov;
double len;
}root[N*6];
inline void Push_up(int t)
{
if(root[t].cov>0) root[t].len=x[root[t].r]-x[root[t].l];
else if(root[t].l+1==root[t].r) root[t].len=0;
else root[t].len=root[t*2].len+root[t*2+1].len;
}
inline void build(int t,int x,int y)
{
root[t].l=x;
root[t].r=y;
root[t].len=0;
root[t].cov=0;
if(x+1==y) return;
int m=(x+y)>>1;
build(t*2,x,m);
build(t*2+1,m,y);
}
inline void Modefiy(int t,int x,int y,int cov)
{
int l=root[t].l;
int r=root[t].r;
int m=(l+r)>>1;
if(l>y||r<x) return;
if(l>=x&&r<=y)
{
root[t].cov+=cov;
Push_up(t);
return;
}
Modefiy(t*2,x,y,cov);
Modefiy(t*2+1,x,y,cov);
Push_up(t);
}
int main()
{
int tCase=1;
while(scanf("%d",&n)&&n)
{
m.clear();
int k=0,i,h=1;
for(i=0;i<n;i++)
{
scanf("%lf%lf%lf%lf",&x1,&y,&x2,&y2);
l[k].cov=1,l[k].x1=x1,l[k].x2=x2,l[k++].y=y;
l[k].cov=-1,l[k].x1=x1,l[k].x2=x2,l[k++].y=y2;
if(m[x1]==0) m[x1]=1;
if(m[x2]==0) m[x2]=1;
}
map<double,int>::iterator it=m.begin();
for(;it!=m.end();++it)
{
x[h]=(*it).first;
m[(*it).first]=h;
h++;
}
sort(l,l+k,cmp);
build(1,1,h);
double ans=0;
printf("Test case #%d\n",tCase++);
for(int i=0;i+1<k;i++)
{
int a=m[l[i].x1];
int b=m[l[i].x2];
Modefiy(1,a,b,l[i].cov);
ans+=(l[i+1].y-l[i].y)*root[1].len;
}
printf("Total explored area: %.2lf\n\n",ans);
}
return 0;
}