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

被折叠的 条评论
为什么被折叠?



