HDU1542(线段树+扫描线)

题目大意:求矩形面积并集。

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<string>
#include<cmath>
#include<list>
using namespace std;
#define lson o<<1,l,m
#define rson o<<1|1,m+1,r
const int maxn=1005;
struct segment
{
    double l,r,h;
    int f;
}seg[maxn<<2];
struct node
{
    int l,r;
    int cover;
    double len;
}tot[maxn<<2];
double pos[maxn<<2];
int num;
bool cmp(segment a,segment b)
{
    return a.h<b.h;
}
void build(int o,int l,int r)
{
    tot[o].l=l;
    tot[o].r=r;
    tot[o].cover=0;
    tot[o].len=0;
    if(l==r)
        return;
    int m=(tot[o].l+tot[o].r)>>1;
    build(lson);
    build(rson);
}
int binary(double x,int low,int high)
{
    while(low<=high)
    {
        int m=(low+high)>>1;
        if(pos[m]==x)
            return m;
        else if(x<pos[m])
            high=m-1;
        else
            low=m+1;
    }
    return -1;
}
void pushup(int o)
{
    if(tot[o].cover)
        tot[o].len=pos[tot[o].r+1]-pos[tot[o].l];
    else if(tot[o].l==tot[o].r)
        tot[o].len=0;
    else
        tot[o].len=tot[o<<1].len+tot[o<<1|1].len ;
}
void update(int o,int l,int r,int v)
{
    if(tot[o].l==l&&tot[o].r==r)
    {
        tot[o].cover=tot[o].cover+v;
        pushup(o);
        return;
    }
    int m=(tot[o].l+tot[o].r)>>1;
    if(r<=m)
        update(o<<1,l,r,v);
    else if(l>m)
        update(o<<1|1,l,r,v);
    else
    {
        update(lson,v);
        update(rson,v);
    }
    pushup(o);
}
int main()
{
    int n;
    int kase=0;
    double x1,y1,x2,y2;
    while(scanf("%d",&n)&&n)
    {
        num=0;
        for(int i=0;i<n;i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            seg[num].l=x1;
            seg[num].r=x2;
            seg[num].h=y1;
            seg[num].f=1;
            seg[num+1].l=x1;
            seg[num+1].r=x2;
            seg[num+1].h=y2;
            seg[num+1].f=-1;
            pos[num]=x1;
            pos[num+1]=x2;
            num+=2;
        }
        sort(seg,seg+num,cmp);
        sort(pos,pos+num);
        int m=1;
        for(int i=1;i<num;i++)
            if(pos[i]!=pos[i-1])
                pos[m++]=pos[i];
        build(1,0,m-1);
        double ans=0;
        for(int i=0;i<num;i++)
        {
            int l=binary(seg[i].l,0,m-1);
            int r=binary(seg[i].r,0,m-1)-1;
            update(1,l,r,seg[i].f);
            ans=ans+(seg[i+1].h-seg[i].h)*tot[1].len;
        }
        printf("Test case #%d\n",++kase);
        printf("Total explored area: %0.2f\n\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值