Problem : 楼房重建

本博客探讨了一个有趣的算法问题:楼房重建。通过使用线段树数据结构,我们能够高效地解决在一系列施工操作后,从特定位置观察到的可见楼房数量问题。文章详细解释了算法的实现细节,并提供了完整的代码示例。

Problem I: 楼房重建

Time Limit: 5 Sec Memory Limit: 256 MB
[Submit][Status][Web Board]

Description

小A的楼房外有一大片施工工地,工地上有N栋待建的楼房。每天,这片工地上的房子拆了又建、建了又拆。他经常无聊地看着窗外发呆,数自己能够看到多少栋房子。为了简化问题,我们考虑这些事件发生在一个二维平面上。小A在平面上(0,0)点的位置,第i栋楼房可以用一条连接(i,0)和(i,Hi)的线段表示,其中Hi为第i栋楼房的高度。如果这栋楼房上任何一个高度大于0的点与(0,0)的连线没有与之前的线段相交,那么这栋楼房就被认为是可见的。施工队的建造总共进行了M天。初始时,所有楼房都还没有开始建造,它们的高度均为0。在第i天,建筑队将会将横坐标为Xi的房屋的高度变为Yi(高度可以比原来大—修建,也可以比原来小—拆除,甚至可以保持不变—建筑队这天什么事也没做)。请你帮小A数数每天在建筑队完工之后,他能看到多少栋楼房?

Input

  • 第一行两个正整数N,M
  • 接下来M行,每行两个正整数Xi,Yi
  • 对于所有的数据1<=Xi<=N,1<=Yi<=10^9
  • N,M<=100000

Output

  • M行,第i行一个整数表示第i天过后小A能看到的楼房有多少栋

Sample Input

3 4
2 4
3 6
1 1000000000
1 1

Sample Output

1
1
1
2

HINT

存好每个点的子树的最大 斜率(不是高度) 和能被看到的建筑数。
直线的斜率一定严格大于他前面所有直线的斜率。

Code

#include <cstdio>
#include <cstring>
using namespace std;
namespace seg {
	struct node {
		double MS; /* Greatest slope of its subtree. */
		int seen; /* The number of the buildings which can be seen. */
	};
	struct segment {
#define lc (now << 1)
#define rc (now << 1 | 1)
		node tree[400001];
		segment() {
			memset(tree, 0, sizeof(tree));
		}
		int get(int now, int l, int r, double slope) {
			if (l == r) {
				return tree[now].seen;
			}
			int mid = (l + r) >> 1;
			if (slope >= tree[lc].MS) {
				return get(rc, mid+1, r, slope); /* None of its subtree will be seen. */
			} else {
				return tree[now].seen - tree[lc].seen + get(lc, l, mid, slope);
			}
		}
		void update(int now, int l, int r) {
			if (tree[lc].MS >= tree[rc].MS) {
				tree[now] = (node) {tree[lc].MS, tree[lc].seen};
			} else {
				int mid = (l + r) >> 1;
				tree[now] = (node) {tree[rc].MS, tree[lc].seen + get(rc, mid + 1, r, tree[lc].MS)};
			}
		}
		void insert(int now, int l, int r, int index, double slope) {
			if (l == r) {
				tree[now] = (node) {slope, 1};
				return;
			}
			int mid = (l + r) >> 1;
			if (index <= mid) {
				insert(lc, l, mid, index, slope);
			} else {
				insert(rc, mid+1, r, index, slope);
			}
			update(now, l, r);
		}
#undef lc
#undef rc
	};
}
int main(int argc, char **argv) {
	int n, m;
	scanf("%d %d", &n, &m);
	seg::segment T;
	for (int i = 1, x, y; i <= m; i++) {
		scanf("%d %d", &x, &y);
		T.insert(1, 1, n, x, 1.0 * y / x);
		printf("%d\n",T.tree[1].seen);
	}
	return 0;
}

[Submit][Status]

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值