HDOJ1255 覆盖的面积 线段树

该博客详细分析了HDOJ1255题目,讨论如何使用线段树来解决覆盖面积的问题。内容包括题目链接、解题思路和通过评测的代码实现,重点在于处理被覆盖至少两次的区间和至少覆盖一次的区间的计算方法。
摘要由CSDN通过智能技术生成

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1255

分析

与普通的面积并不同的是,

我们要维护被覆盖了至少两次的区间,还需同时维护至少覆盖了一次的区间,

后者是很容易维护的,而对于前者来说,

若整个区间被至少覆盖了两次,则结果为区间长度,

否则,若区间长度为 1 1 1,则结果为 0 0 0

否则,若区间被覆盖了一次,则结果为子区间被至少覆盖一次的长度之和,

否则结果为子区间被至少覆盖两次的长度之和。

AC代码

#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 1e3 + 5;

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

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

double x1, y1, x2, y2, a[2 * maxn];

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

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

void build(int p, int l, int r) {
	t[p].l = l, t[p].r = r, t[p].cnt = t[p].len1 = t[p].len2 = 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() {
	int T, n;
	scanf("%d", &T);
	while (T--) {
		scanf("%d", &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);
		int 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 y1 = lower_bound(a + 1, a + m + 1, line[i].y1) - a;
			int y2 = lower_bound(a + 1, a + m + 1, line[i].y2) - a;
			modify(1, y1, y2 - 1, line[i].k);
			ans += t[1].len2 * (line[i + 1].x - line[i].x);
		}
		printf("%.2f\n", ans);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值