【hdu1255】覆盖的面积(矩形面积交+线段树+扫描线)

Description

    给定平面上若干矩形,求出被这些矩形覆盖过至少两次的区域的面积.

Input

    输入数据的第一行是一个正整数T(1<=T<=100),代表测试数据的数量.每个测试数据的第一行是一个正整数N(1<=N<=1000),代表矩形的数量,然后是N行数据,每一行包含四个浮点数,代表平面上的一个矩形的左上角坐标和右下角坐标,矩形的上下边和X轴平行,左右边和Y轴平行.坐标的范围从0到100000.
    注意:本题的输入数据较多,推荐使用scanf读入数据.

Output

    对于每组测试数据,请计算出被这些矩形覆盖过至少两次的区域的面积.结果保留两位小数.

Sample Input

2
5
1 1 4 2
1 3 3 7
2 1.5 5 4.5
3.5 1.25 7.5 4
6 3 10 7
3
0 0 1 1
1 0 2 1
2 0 3 1

Sample Output

7.63
0.00

I think

    题意:求矩形面积交
    算法:线段树+扫描线+离散化
    思路&实现:基本思路同【poj1151】Atlantis(矩形面积并+线段树+扫描线)
    但在本题中求的是面积交而不是并,面积并c[]数组的标记不下传(在分析此类题目是也不要纠结于把它改为能够下传的标记),因此新开一个two[]数组记被覆盖过两次及以上的边的总长,按照同样更新one[]数组的套路更新即可。
    手动四舍五入保留两位小数函数:

#include<cmath>
using namespace std;
double round_off(double x) {
    double tmp=x*100;
    tmp=floor(tmp+0.5);
    return tmp*0.01;
}

Code

#include<cmath>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

const int sm = 2000+50;

int T,t,tt,n;
int c[sm<<2];
double x1,x2,yy,y2,ans;
double one[sm<<2],two[sm<<2],y[sm<<2];
struct line { 
    double x,y1,y2;
    int flag;
}a[sm];

bool cmp(line u,line v) { return u.x<v.x; }
double round_off(double x) {
    double tmp=x*100;
    tmp=floor(tmp+0.5);
    return tmp*0.01;
}
void build(int k,int l,int r) {
    if(l+1==r) { 
        c[k]=one[k]=two[k]=0;return;
    }
    int m=(l+r)>>1;
    build(k<<1,l,m);
    build(k<<1|1,m,r);
    c[k]=one[k]=two[k]=0;
}

void calen (int k,int l,int r) {
    if(c[k]>=2)one[k]=two[k]=y[r]-y[l];
    else if(c[k]==1) { 
        one[k]=y[r]-y[l];
        if(l+1==r) two[k]=0;
        else two[k]=one[k<<1]+one[k<<1|1];
    }
    else {
        if(l+1==r) one[k]=two[k]=0;
        else {
            one[k]=one[k<<1]+one[k<<1|1];
            two[k]=two[k<<1]+two[k<<1|1];
        }
    }
}

void update(int k,int l,int r,line x) {
    if(x.y1<=y[l]&&y[r]<=x.y2) {
        c[k]+=x.flag,calen(k,l,r);
        return;
    }
    if(l+1==r)return;
    int m=(l+r)>>1;
    if(x.y1<=y[m])update(k<<1,l,m,x);
    if(x.y2>y[m])update(k<<1|1,m,r,x);
    calen(k,l,r);
}

int main() {    
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&n);
        ans=t=0;
        for(int i=1;i<=n;++i) {
            scanf("%lf%lf%lf%lf",&x1,&yy,&x2,&y2);
            y[++t]=yy,a[t].x=x1,a[t].y1=yy,a[t].y2=y2,a[t].flag=1;
            y[++t]=y2,a[t].x=x2,a[t].y1=yy,a[t].y2=y2,a[t].flag=-1;
        }
        sort(y+1,y+t+1);
        tt=unique(y+1,y+t+1)-y-1;
        sort(a+1,a+t+1,cmp);
        build(1,1,tt);
        update(1,1,tt,a[1]);    
        for(int i=2;i<=t;++i) {
            ans+=(a[i].x-a[i-1].x)*two[1];
            update(1,1,tt,a[i]);
        }
        printf("%.2lf\n",round_off(ans));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值