HDU-1542 Atlantis

本文介绍了一种使用线段树、扫描线与离散化处理矩形覆盖面积问题的算法实现。通过具体代码示例展示了如何高效计算由多个矩形构成的区域总面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线段树+扫描线+离散化

求矩形覆盖面积扫描线算法的简单模板题

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>

using namespace std;
const int maxn=200+10;

struct line
{
    double x,y1,y2;
    int f;
    bool operator < (const line &u) const
    {
        return x<u.x;
    }
}edge[maxn];
double len[maxn<<2];
int cover[maxn<<2];
double Y[maxn];

void build(int l,int r,int rt)
{
    len[rt]=0.0;
    cover[rt]=0;
    if(r-l==1) return;
    int m=(l+r+1)>>1;
    build(l,m,rt<<1);
    build(m,r,rt<<1|1);
}

void PushUp(int rt,int l,int r)
{
    if(cover[rt]>0)
    {
        len[rt]=Y[r]-Y[l];
    }
    else if(r-l==1)
    {
        len[rt]=0.0;
    }
    else
    {
        len[rt]=len[rt<<1]+len[rt<<1|1];
    }
}

void update(double L,double R,int f,int l,int r,int rt)
{
    if(Y[l]>=L&&Y[r]<=R)
    {
        cover[rt]+=f;
    }
    else
    {
        int m=(l+r+1)>>1;
        if(L<Y[m]) update(L,R,f,l,m,rt<<1);
        if(R>Y[m]) update(L,R,f,m,r,rt<<1|1);
    }
    PushUp(rt,l,r);
}

int main()
{
    //freopen("/home/zlwang/test.txt","r",stdin);
    int n,kase=0;
    while(~scanf("%d",&n))
    {
        if(n==0) break;
        double x1,x2,y1,y2;
        int cnt=0;
        for(int i=0;i<n;i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            Y[i]=y1;
            Y[n+i]=y2;
            edge[cnt].y1=y1;
            edge[cnt].y2=y2;
            edge[cnt].x=x1;
            edge[cnt].f=1;
            cnt++;
            edge[cnt].y1=y1;
            edge[cnt].y2=y2;
            edge[cnt].x=x2;
            edge[cnt].f=-1;
            cnt++;
        }
        sort(edge,edge+2*n);
        sort(Y,Y+2*n);
        cnt=1;
        for(int i=1;i<2*n;i++)
        if(Y[i]!=Y[i-1]) Y[cnt++]=Y[i];
        build(0,cnt-1,1);
        double ans=0.0;
        for(int i=0;i<2*n-1;i++)
        {
            update(edge[i].y1,edge[i].y2,edge[i].f,0,cnt-1,1);
            ans+=len[1]*(double)(edge[i+1].x-edge[i].x);
        }
        printf("Test case #%d\n",++kase);
        printf("Total explored area: %.2f\n\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值