扫描线模板代码详讲Atlantis

HDU1542Atlantis
题意:
求矩形块总面积,给定n个矩形坐标(左下角和右上角坐标),坐标有可能是小数。
分析:本题是一道扫描线模板问题。
扫描线就是按照x轴或者y轴的一个方向去扫描维护整个y值或x值所对应的线段总长。例如:矩形a:(1,1)(3,3)矩形b:(4,1)(6,3),当y=1时线段总长度为4,y=3时总长度为4;
利用线段树来维护,线段的长度。
有些情况需要对数据离散化处理。
在本题中只需要对y轴进行扫描即可,再利用线段树维护区间的长度,面积直接用线段的长度乘上高就行了。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#define ml root<<1
#define mr root<<1|1
#define dou double
using namespace std;
const int N=1e5+55;
dou pox[N];  //离散化数组;
struct node{
    dou sum;
    int val;
}tr[N];        //线段树维护sum为线段长度,val来标记上下底边用以消边。
struct nod{
    dou x1,x2,y;
    int val;
    nod(dou a=0,dou b=0,dou c=0,int d=0):x1(a),x2(b),y(c),val(d){}
    friend bool operator <(nod a, nod b)
    {
        return a.y<b.y;
    }
}mp[N];   //记录每一条线段,并按y轴上升序列排序;
void update(int root, int l, int r)  //维护线段树节点;
{
    if(tr[root].val) tr[root].sum=pox[r+1]-pox[l]; //这儿用r+1因为对于线段树mid和mid+1它们之间也是有距离的,如果用r的话mid到mid+1就不会算上。所以下面要用r-1(多加了一个就减去一个)
    else if(l==r) tr[root].sum=0;
    else tr[root].sum=tr[ml].sum+tr[mr].sum;   //消去线段和向上回溯维护线段树;
} 
void add_(int root, int l, int r, int s, int t,int val) //标准线段树维护;
{
    if(l==s&&r==t){
        tr[root].val+=val;
        update(root,l,r);
        return ;
    }
    int mid=(l+r)/2;
    if(t<=mid) add_(ml,l,mid,s,t,val);
    else if(s>mid) add_(mr,mid+1,r,s,t,val);
    else{
        add_(ml,l,mid,s,mid,val);
        add_(mr,mid+1,r,mid+1,t,val);
    }
    update(root,l,r);
}
int main()
{
    int n,t=0;
    while(scanf("%d",&n)!=EOF&&n) {
        int tot = 1;
        dou x1, x2, y1, y2, ans = 0;
        for (int i = 1; i <= n; ++i) {   //录入数据;
            scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
            mp[tot] = nod(x1, x2, y1, 1);
            pox[tot++] = x1;
            mp[tot] = nod(x1, x2, y2, -1);
            pox[tot++] = x2;
        }
        sort(pox + 1, pox + tot);
        sort(mp + 1, mp + tot);
        int tx = 2;
        for (int i = 2; i < tot; ++i) {   //离散化处理;
            if (pox[i] != pox[i - 1]) pox[tx++] = pox[i];
        }
        tot--;   //因为最后一层不需要处理;
        for (int i = 0; i < N; ++i) tr[i].sum = tr[i].val = 0;  //初始化线段树;
        for (int i = 1; i < tot; ++i) {
            int l = lower_bound(pox + 1, pox + tx, mp[i].x1) - pox;
            int r = lower_bound(pox + 1, pox + tx, mp[i].x2) - pox;
            add_(1, 1, tx, l, r-1, mp[i].val);       //这儿为什么用r-1在update()函数中已说明;
            ans += tr[1].sum * (mp[i + 1].y - mp[i].y);  //计算面积;
        }
        printf("Test case #%d\n",++t);
        printf("Total explored area: %.2f\n", ans);
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值