POJ1151 Atlantis 线段树

题目链接

http://poj.org/problem?id=1151

分析

扫描线求矩形面积并,以从左向右扫描为例,

将矩形拆成 2 n 2n 2n 条竖直线段,用线段树来维护当前有效长度,

遇到某个矩形左侧的线段,则尝试增加有效长度,右侧则尝试减小有效长度;

每次用有效长度乘线段间隔来累加答案。

AC代码

#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 105;

struct Line {
	int k;
	double x, y1, y2;

	bool operator < (const Line& rhs) const {
		return x < rhs.x;
	}
} line[2 * maxn];

int n, m, id;
double x1, y1, x2, y2, a[2 * maxn];

struct SegmentTree {
	int l, r, cnt;
	double len;
} t[8 * maxn];

inline void up(int p) {
	if (t[p].cnt) t[p].len = a[t[p].r + 1] - a[t[p].l];
	else if (t[p].l == t[p].r) t[p].len = 0;
	else t[p].len = t[2 * p].len + t[2 * p + 1].len;
}

void build(int p, int l, int r) {
	t[p].l = l, t[p].r = r, t[p].cnt = t[p].len = 0;
	if (l == r) return;
	int mid = (l + r) >> 1;
	build(2 * p, l, mid);
	build(2 * p + 1, mid + 1, r);
}

void modify(int p, int l, int r, int d) {
	if (l <= t[p].l && t[p].r <= r) {
		t[p].cnt += d, up(p);
		return;
	}
	int mid = (t[p].l + t[p].r) >> 1;
	if (l <= mid) modify(2 * p, l, r, d);
	if (r > mid) modify(2 * p + 1, l, r, d);
	up(p);
}

int main() {
	while (scanf("%d", &n) == 1 && n) {
		for (int i = 1; i <= n; ++i) {
			scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
			line[i] = (Line){1, x1, y1, y2}, line[i + n] = (Line){-1, x2, y1, y2};
			a[i] = y1, a[i + n] = y2;
		}
		sort(line + 1, line + 2 * n + 1);
		sort(a + 1, a + 2 * n + 1);
		m = unique(a + 1, a + 2 * n + 1) - a - 1;
		build(1, 1, m - 1);
		double ans = 0;
		for (int i = 1; i < 2 * n; ++i) {
			int l = lower_bound(a + 1, a + m + 1, line[i].y1) - a;
			int r = lower_bound(a + 1, a + m + 1, line[i].y2) - a;
			modify(1, l, r - 1, line[i].k);
			ans += t[1].len * (line[i + 1].x - line[i].x);
		}
		printf("Test case #%d\nTotal explored area: %.2f\n\n", ++id, ans);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值