POJ 1151 & HDU 1542 Atlantis (扫描线+线段树+离散化)

题意:n个矩形,给出左下、右上坐标,求最后总的面积。

题解:扫描线+线段树+离散化
第一道扫描线。

我们从下至上扫描,离散化横坐标。

扫描之前还需要做一个工作,就是保存好所有矩形的上下边,并且按照它们所处的高度进行排序,另外如果是上边就是-1,相当于总区间上删除一段,也就是出边;下边给就是1,相当于往总区间上插入一段,也就是入边。

我们每次往线段树里加一条入边,也就是在不断更新总的底边长度(增加或减少),直到下一条边是出边,那么我们可以累加面积。如何判断下一条边是出边呢?

由于我们记录了每条边的高度,用e[i + 1].h - e[i].h判断即可,若该值为0,则还没更新完毕;若值为负数,那么线段树根的值必为0,因为已经将所有边添加完毕了;正数就是正常情况。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
//扫描线 从下至上
const int MAXN = 222;
struct Seg {
    double l, r, h;  //入边、出边的左右横坐标,以及高度
    int flag;  //标记入边1 出边-1
    Seg() {}
    Seg(double a, double b, double c, int d) :l(a), r(b), h(c), flag(d) {}
    bool operator < (const Seg& cmp) const {
        return h < cmp.h;
    }
}e[MAXN];
struct node {
    int cnt;
    double len;
} tree[MAXN << 2];
double X[MAXN];
void pushUp(int l, int r, int rt) {
    if (tree[rt].cnt)//当前的边被标记,就把当前的长度加上
        tree[rt].len = X[r + 1] - X[l];
    else if (l == r)//当为一个点的时候长度为0
        tree[rt].len = 0;
    else//其他情况把左右两个区间的值加上
        tree[rt].len = tree[rt << 1].len + tree[rt << 1 | 1].len;
}
void update(int L, int R, int l, int r, int rt, int val) {
    if (L <= l && r <= R) {
        tree[rt].cnt += val;  //加上标记的值
        pushUp(l, r, rt);
        return;
    }
    int m = (l + r) >> 1;
    if (L <= m) update(L, R, l, m, rt << 1, val);
    if (R > m) update(L, R, m + 1, r, rt << 1 | 1, val);
    pushUp(l, r, rt);
}
int n;
double xa, ya, xb, yb;
int main() {
    int cas = 0;
	while (~scanf("%d", &n) && n) {
        memset(tree, 0, sizeof(tree));
        int num = 0;
		for (int i = 1; i <= n; i++) {
			scanf("%lf%lf%lf%lf", &xa, &ya, &xb, &yb);
            X[num] = xa;
            e[num++] = Seg(xa, xb, ya, 1); //ya 入边
            X[num] = xb;
            e[num++] = Seg(xa, xb, yb, -1); //yb 出边
		}
        sort(X, X + num);
        sort(e, e + num);
        int len = unique(X, X + num) - X;
        double ans = 0;
        for (int i = 0; i < num; i++) {
            int l = lower_bound(X, X + len, e[i].l) - X;
            int r = lower_bound(X, X + len, e[i].r) - X;
            update(l, r - 1, 0, len, 1, e[i].flag);
            //cout << tree[1].len << " " << e[i + 1].h - e[i].h << endl;
            ans += tree[1].len * (e[i + 1].h - e[i].h);
        }
        printf("Test case #%d\nTotal explored area: %.2f\n\n", ++cas, ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值