题意:
给你直角坐标系上的n个矩形,求其覆盖的总面积。
思路:
屏幕面积并问题,离散坐标后,用线段树实现扫描法。
我对扫描法的一点理解:
就是从高度最低开始扫描,用线段树维护当前高度向上的有面积覆盖的总长度,然后一层一层的求面积。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000+7;
int n,cnt,num[maxn*8];
double sum[maxn*8],x[maxn*2];
struct edge
{
double l,r,h;
int f;
bool operator < (const edge &cmp) const
{
return h<cmp.h;
}
}e[maxn*2];
void add(double x1,double y1,double x2,double y2)
{
e[cnt].l = x1;
e[cnt].r = x2;
e[cnt].h = y1;
e[cnt].f = 1;
cnt++;
e[cnt].l = x1;
e[cnt].r = x2;
e[cnt].h = y2;
e[cnt].f = -1;
cnt++;
}
void pushdown(int l,int r,int rt)
{
if(num[rt])
sum[rt] = x[r+1]-x[l];
else if(l==r)
sum[rt] = 0;
else
sum[rt] = sum[rt<<1]+sum[rt<<1|1];
}
void update(int rt,int l,int r,int ql,int qr,int v)
{
if(ql<=l&&r<=qr)
{
num[rt]+=v;
pushdown(l,r,rt);
return ;
}
int mid = (l+r)>>1;
if(ql<=mid)
update(rt<<1,l,mid,ql,qr,v);
if(qr>mid)
update(rt<<1|1,mid+1,r,ql,qr,v);
pushdown(l,r,rt);
}
int main()
{
while(~scanf("%d",&n)&&n)
{
cnt = 0;
memset(num,0,sizeof(num));
memset(sum,0,sizeof(sum));
for(int i = 0;i<n;i++)
{
double x1,y1,x2,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
x[i] = x1;
x[n+i] = x2;
add(x1,y1,x2,y2);
}
sort(x,x+n*2);
sort(e,e+n*2);
int m = 0;
for(int i = 1;i<n*2;i++)
{
if(x[i]!=x[i-1])
x[++m] = x[i];
}
double ans = 0;
for(int i = 0;i<n*2-1;i++)
{
int ql = lower_bound(x,x+m+1,e[i].l)-x;
int qr = lower_bound(x,x+m+1,e[i].r)-x-1;
//cout<<ql<<" "<<qr<<" "<<m-1<<" "<<e[i].f<<endl;
if(ql<=qr)
update(1,0,m-1,ql,qr,e[i].f);
ans += sum[1]*(e[i+1].h-e[i].h);
//cout<<ans<<endl;
}
printf("%.0f\n",ans);
}
puts("*");
return 0;
}