POJ_2482
这个题目类似黑书上的一个例题,在看了黑书的那个例题之后,以及做过前面关于扫面线的相关练习之后,这个题目的思路就不难理解了。
首先我们要控制矩形横向的位置,完成这一点可以用一个队列,当队尾的x和队首的x之差大于或等于W就让队首的点出队即可。接下来,就是考虑如果矩形从下往上滑动时,在哪个位置所圈的星星的总亮度最高呢?黑书上介绍了算法,我们可以把每个星星按纵坐标的拆成两个点,一个是y,一个是y+H,如果y点亮度为z的话,那么y+H点的亮度就是-z,这样求y方向上的最大前缀和就得到了最高的总亮度,所以我们需要用一棵线段树维护各个前缀和,并能够查询所有前缀和的最大值。
更多和线段树、扫描线相关的题目可以参考胡浩的博客:http://www.notonlysuccess.com/index.php/segment-tree-complete/。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAXD 20010 struct Point { int x, y, z; }point[MAXD]; int N, M, W, H, max[4 * MAXD], add[4 * MAXD]; long long int ty[MAXD]; int cmpy(const void *_p, const void *_q) { long long int *p = (long long int *)_p, *q = (long long int *)_q; return *p < *q ? -1 : 1; } int cmpp(const void *_p, const void *_q) { Point *p = (Point *)_p, *q = (Point *)_q; return p->x < q->x ? -1 : 1; } void build(int cur, int x, int y) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; max[cur] = add[cur] = 0; if(x == y) return ; build(ls, x, mid); build(rs, mid + 1, y); } void init() { int i, j, k; for(i = 0; i < N; i ++) { j = i << 1, k = (i << 1) | 1; scanf("%d%d%d", &point[i].x, &point[i].y, &point[i].z); ty[j] = point[i].y, ty[j + 1] = (long long int)point[i].y + H; } qsort(ty, N << 1, sizeof(ty[0]), cmpy); M = 0; for(i = 0; i < (N << 1); i ++) if(i == 0 || ty[i] != ty[i - 1]) ty[M ++] = ty[i]; build(1, 0, M - 1); } int BS(long long int x) { int min = 0, max = M, mid; for(;;) { mid = (max + min) >> 1; if(mid == min) break; if(ty[mid] <= x) min = mid; else max = mid; } return mid; } void update(int cur) { int ls = cur << 1, rs = (cur << 1) | 1; max[cur] = max[ls] > max[rs] ? max[ls] : max[rs]; } void pushdown(int cur) { int ls = cur << 1, rs = (cur << 1) | 1; if(add[cur]) { add[ls] += add[cur], add[rs] += add[cur]; max[ls] += add[cur], max[rs] += add[cur]; add[cur] = 0; } } void refresh(int cur, int x, int y, int s, int t, int delta) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; if(x >= s && y <= t) { max[cur] += delta, add[cur] += delta; return ; } pushdown(cur); if(mid >= s) refresh(ls, x, mid, s, t, delta); if(mid + 1 <= t) refresh(rs, mid + 1, y, s, t, delta); update(cur); } void solve() { int i, j, k, l, r, ans = 0; qsort(point, N, sizeof(point[0]), cmpp); for(i = j = 0; i < N; i ++) { l = BS(point[i].y), r = BS((long long int)point[i].y + H); refresh(1, 0, M - 1, l, M - 1, point[i].z), refresh(1, 0, M - 1, r, M - 1, -point[i].z); while(point[j].x <= point[i].x - W) { l = BS(point[j].y), r = BS((long long int)point[j].y + H); refresh(1, 0, M - 1, l, M - 1, -point[j].z), refresh(1, 0, M - 1, r, M - 1, point[j].z); ++ j; } if(max[1] > ans) ans = max[1]; } printf("%d\n", ans); } int main() { while(scanf("%d%d%d", &N, &W, &H) == 3) { init(); solve(); } return 0; }