我是靠谱客的博主 优美唇彩,这篇文章主要介绍HDU 1828 Picture(矩形周长的并+扫描线+离散化),现在分享给大家,希望可以做个参考。

题意:

求N个矩形周长的并。

解析:

矩形周长的并会比面积并难一些,但是理解之后发现也不是很难。
参考这篇题解

先离散化 x 坐标,按y从下到上扫描。
统计每次加入一条扫描线总和的增加值
总和增加值 = 横向边增加的长度 + 纵向边增加的长度
pre 表示之前加入横向边时的长度, sum[1] 是利用线段树维护的当前横边的长度。
这样可以用线段树维护横向边增加的长度 |sum[1]pre|
对于纵向边增加的长度,为 (line[i+1].hline[i].h)segnum[1]
前面的 (line[i+1].hline[i].h) 表示相邻的两条扫描线的 y 坐标的差,segnum[1]代表此时在线段树中一共有几条竖边。
所以只要统计到当前有多少条竖边,就可以得到那一段的纵向边增加长度。

统计某一时刻有多少条竖边,
可以用 lc rc 记录这一个节点的两个端点是不是已经覆盖,如果覆盖值为 true
lc rc 用来判断两个矩形是否相交,合并两个节点的时候,父节点的 segnum 等于左右子节点的 segnum 和,如果左节点的 rc 与右节点的 lc 都是true,表示两个矩形相交,那么父节点的 segnum 减去2,表示竖边的个数应该减去2。

my code

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <cstdio> #include <cstring> #include <algorithm> #include <cstdlib> #define ls (o<<1) #define rs (o<<1|1) #define lson ls, L, M #define rson rs, M+1, R #define MID (L + R) >> 1 using namespace std; const int N = (int)1e4 + 10; struct Line { int l, r, h, d; bool operator < (const Line &rhs) const { if(h == rhs.h) return d > rhs.d; return h < rhs.h; } } line[N]; int n, m, tot; int X[N]; int cov[N<<2], sum[N<<2], segnum[N<<2]; bool lc[N<<2], rc[N<<2]; int search(int x) { int L = 0, R = tot-1; while(L <= R) { int M = MID; if(X[M] == x) return M; if(X[M] < x) L = M + 1; else R = M - 1; } return -1; } void build(int o, int L, int R) { cov[o] = sum[o] = segnum[o] = 0; lc[o] = rc[o] = false; if(L == R) return ; int M = MID; build(lson); build(rson); } void pushUp(int o, int L, int R) { if(cov[o]) { sum[o] = X[R+1] - X[L]; lc[o] = rc[o] = true; segnum[o] = 2; }else if(L == R) { sum[o] = segnum[o] = 0; lc[o] = rc[o] = false; }else { sum[o] = sum[ls] + sum[rs]; segnum[o] = segnum[ls] + segnum[rs]; lc[o] = lc[ls], rc[o] = rc[rs]; if(rc[ls] && lc[rs]) segnum[o] -= 2; } } void modify(int o, int L, int R, int ql, int qr, int d) { if(ql <= L && R <= qr) { cov[o] += d; pushUp(o, L, R); return ; } int M = MID; if(ql <= M) modify(lson, ql, qr, d); if(qr > M) modify(rson, ql, qr, d); pushUp(o, L, R); } int main() { int x1, y1, x2, y2; while(~scanf("%d", &n)) { m = tot = 0; for(int i = 0; i < n; i++) { scanf("%d%d%d%d", &x1, &y1, &x2, &y2); line[m] = (Line){x1, x2, y1, 1}; X[m++] = x1; line[m] = (Line){x1, x2, y2, -1}; X[m++] = x2; } sort(line, line+m); sort(X, X+m); tot = unique(X, X+m) - X; build(1, 0, tot-1); int pre = 0, ans = 0, w, h; int ql, qr; for(int i = 0; i < m; i++) { ql = search(line[i].l), qr = search(line[i].r) - 1; modify(1, 0, tot-1, ql, qr, line[i].d); h = line[i+1].h - line[i].h; w = abs(sum[1] - pre); ans += (w + h * segnum[1]); pre = sum[1]; } printf("%dn", ans); } return 0; }

最后

以上就是优美唇彩最近收集整理的关于HDU 1828 Picture(矩形周长的并+扫描线+离散化)的全部内容,更多相关HDU内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部