Atlantis HDU - 1542 线段树+扫描线求面积并

一点心得:

这一题是我学扫描线的第一题,扫描线的原理是比较好理解的,主要是离散化坐标后用线段树维护x或是y轴上的线段,乘以扫描线所经过的距离就是面积了。
这里有一个我看到的解释扫描线的博客:扫描线的解释 >”<
我感觉的话扫描线主要难的地方,一定要选点靠谱的代码~刚开始一直在看某个博主的奇技淫巧~T_T,一直没看懂。后来换了代码,就很容易懂了。这里给出这位大神的Blog:HDU - 1542 >”<
emmm,然后就是我这个弱鸡的代码喽~毕竟自己写的代码比较符合自己的风格,会舒服很多哦~
由于这题条件特殊,所以没有去除重复部分的操作~

代码:

#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1e3+9;
double y[MAX_N];
struct Line
{
    double x,y1,y2; // y1 < y2
    int flag;
}line[300];
struct Node
{
    int l,r,cover;
    double lf,rf,len;
}node[MAX_N];
bool cmp(const Line & A,const Line & B)
{
    return A.x < B.x;
}
void build(int rt,int l,int r)
{
    node[rt].l = l; node[rt].r = r;
    node[rt].lf = y[l]; node[rt].rf = y[r];
    node[rt].len = node[rt].cover = 0;
    if(l+1 == r) return ;
    int mid = (l+r) >> 1;
    build(rt<<1,l,mid);
    build(rt<<1|1,mid,r);
}
void push_up(int rt)
{
    if(node[rt].cover > 0)
    {
        node[rt].len = node[rt].rf - node[rt].lf;
        return;
    }
    else if(node[rt].l+1 == node[rt].r)
    {
        node[rt].len = 0;
    }
    else
    {
        node[rt].len = node[rt<<1].len + node[rt<<1|1].len;
    }
}
void updata(int rt,Line t)
{
    if(t.y1 == node[rt].lf && t.y2 == node[rt].rf)
    {
        node[rt].cover += t.flag;
        push_up(rt);
        return;
    }

    if(t.y1 >= node[rt<<1|1].lf)
    {
        updata(rt<<1|1 , t);
    }
    else if(t.y2 <= node[rt<<1].rf)
    {
        updata(rt<<1 , t);
    }
    else
    {
        Line temp = t;
        temp.y2 = node[rt<<1].rf;
        updata(rt<<1 , temp);
        temp = t;
        temp.y1 = node[rt<<1|1].lf;
        updata(rt<<1|1 , temp);
    }
    push_up(rt);
}

int main()
{
    int N,M,T=1;
    while(cin>>N)
    {
        if(N==0) break;
        int cnt = 0;
        for(int i=0;i<N;i++)
        {
            double x1,y1,x2,y2;
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            line[cnt].x = x1;
            line[cnt].y1 = y1;
            line[cnt].y2 = y2;
            line[cnt].flag = 1;
            y[cnt++] = y1;
            line[cnt].x = x2;
            line[cnt].y1 = y1;
            line[cnt].y2 = y2;
            line[cnt].flag = -1;
            y[cnt++] = y2;
        }
        sort(line,line+cnt,cmp);
        sort(y,y+cnt);
        build(1,0,cnt-1);
        updata(1,line[0]);
        double ans = 0;
        for(int i=1;i<cnt;i++)
        {
            ans += node[1].len*(line[i].x - line[i-1].x);
            updata(1,line[i]);
        }
        cout<<"Test case #"<<T<<endl;
        printf("Total explored area: %.2lf\n\n",ans);
        T++;
    }
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值