【线段树 面积并 扫描线】HDU - 1542 Atlantis

Problem Description

输入一个n,给你n个矩阵的左下角坐标,和右上角坐标。让你求所有面积并的和。

思路:

扫描线参考博客:http://www.cnblogs.com/scau20110726/archive/2013/04/12/3016765.html
博客是从下到上扫描,个人习惯从左到右扫描。我们左边扫描过来的有效长度设为len,那么线段树就是维护区间最长len,还有cover值(用来标记该区间的整段线段是否有效,大于0的时候有效,等于0的时候无效,根据扫描线博客)。

#include<bits/stdc++.h>
using namespace std;
#define lson root<<1
#define rson root<<1|1
#define N 105
#define MID int mid = (l + r) / 2
struct node
{
    int cover;
    double len;
};
node tree[N<<3];//线段树
double yy[N<<2];//用来存所有点的纵坐标
struct Node
{
    int cover;//左边是1,右边是-1.
    double x;//该点的横坐标
    double yd, yu;//下纵,上纵坐标
    bool operator < (const Node &b) const{
        return x < b.x;
    }
};
Node a[N<<2];//存各点的数据
void build(int root, int l, int r)
{
    tree[root].cover = tree[root].len = 0;//该区间线段无效所以0,有效长度0
    if(l + 1 == r)
        return;
    MID;
    build(lson, l, mid);
    build(rson, mid, r);
}
void get_len(int root, int l, int r)
{
    if(tree[root].cover)//该区间整段有效
        tree[root].len = yy[r] - yy[l];
    else if(l + 1 == r)//叶子节点,同时区间无效
        tree[root].len = 0;
    else tree[root].len = tree[lson].len + tree[rson].len;//左右儿子len的和
}
void updata(int root, int l, int r, int ul, int ur, int cover)
{
    if(ul <= l && r <= ur)//更新cover,len
    {
        tree[root].cover += cover;
        get_len(root, l, r);
        return;
    }
    MID;
    if(ul < mid) updata(lson, l, mid, ul, ur, cover);
    if(ur > mid) updata(rson, mid, r, ul, ur, cover);
    get_len(root, l, r);//归并,向上更新
}
int main()
{
    int n, cnt, i, cas = 1;
    double x1, x2, y1, y2;
    while(~scanf("%d", &n) && n)
    {
        cnt = 0;
        for(i = 0; i < n; i++)
        {
            scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
            yy[cnt] = y1;
            a[cnt++] = ((Node){1, x1, y1, y2});//左下角
            yy[cnt] = y2;
            a[cnt++] = ((Node){-1, x2, y1, y2});//右上角
        }
        sort(yy, yy + cnt);//离散化一下
        n = unique(yy, yy + cnt) - yy;
        build(1, 0, n - 1);//初始化建树,0-(n-1)是离散化后对应的最小yy到最大yy的范围
        sort(a, a + cnt);//按x从小到大排序
        int ul, ur;
        double ans = 0;
        for(i = 0; i < cnt - 1; i++)
        {
            ul = lower_bound(yy, yy + n, a[i].yd) - yy;
            ur = lower_bound(yy, yy + n, a[i].yu) - yy;
            updata(1, 0, n - 1, ul, ur, a[i].cover);//每次更新有效长度
            ans += tree[1].len * (a[i + 1].x - a[i].x);//有效长度是底边,有效长度×高是面积。
        }
        printf("Test case #%d\n", cas++);
        printf("Total explored area: %.2lf\n\n", ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值