HDU 1698

题目链接:

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

题目描述:

  有一条长度为N的链,该链每一个单位长度的价值都是1。现有Q个操作,每个操作包括三个数字X, Y, Z, 表示将链中X ~ Y这一段每个单位长度的价值全部改变为Z,注意不是添加Z而是改变为Z。最后问该链的总价值是多少。

解题思路:

  区间的线段树更新问题,区间更新线段树跟点更新线段树的最主要区别同时也是最难过的坎就是延迟标记lazy数组,不过看完这个ppt:http://yun.baidu.com/s/1jGXToME就可以理解延迟标记是什么意思了。理解了之后就可以自己写出来拉。

  线段树的原理其实说白了也就那样,真正的熟悉方法很简单,把模版打上十遍,自然就熟悉线段树了。

附代码:

 1 #include <iostream>
 2 #include <cmath>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <map>
 6 #include <vector>
 7 #include <algorithm>
 8 using namespace std;
 9 
10 #define ll long long
11 #define INF 0x3f3f3f3f
12 #define LL_INF 0x3f3f3f3f3f3f3f3f
13 #define lson l, m, rt << 1
14 #define rson m + 1, r, rt << 1|1
15 #define lrt rt << 1
16 #define rrt rt << 1|1
17 #define MAX 1001000
18 
19 struct SegTree
20 {
21     int left, right;
22     int sum, lazy;
23     inline int len() { return right - left + 1; }
24 }SegNode[MAX << 2];
25 
26 void pushUp(int rt)
27 {
28     SegNode[rt].sum = SegNode[rt << 1].sum + SegNode[rt << 1|1].sum;
29 }
30 
31 void pushDown(int rt)
32 {
33     if(!SegNode[rt].lazy) return;
34     SegNode[lrt].sum = SegNode[lrt].len() * SegNode[rt].lazy;
35     SegNode[rrt].sum = SegNode[rrt].len() * SegNode[rt].lazy;
36     SegNode[lrt].lazy = SegNode[rt].lazy;
37     SegNode[rrt].lazy = SegNode[rt].lazy;
38     SegNode[rt].lazy = 0;
39 }
40 
41 void build(int l, int r, int rt)
42 {
43     SegNode[rt].sum = 1;
44     SegNode[rt].lazy = 0;
45     if(l == r) {
46         SegNode[rt].left = l;
47         SegNode[rt].right = r;
48         //printf("%d %d %d
", rt, l, r);
49         return;
50     }
51     int m = (l + r) >> 1;
52     build(lson);
53     build(rson);
54     pushUp(rt);
55     SegNode[rt].left = l;
56     SegNode[rt].right = r;
57     //printf("%d %d %d
", rt, l, r);
58 }
59 
60 void update(int change, int l, int r, int rt)
61 {
62     if(SegNode[rt].left == l && SegNode[rt].right == r) {
63         SegNode[rt].sum = SegNode[rt].len() * change;
64         SegNode[rt].lazy = change;
65         return;
66     }
67     pushDown(rt);
68     int m = (SegNode[rt].left + SegNode[rt].right) >> 1;
69     if(r <= m)
70         update(change, l, r, lrt);
71     else if(l > m)
72         update(change, l, r, rrt);
73     else {
74         update(change, lson);
75         update(change, rson);
76     }
77     pushUp(rt);
78 }
79 
80 int main()
81 {
82     //freopen("debug\in.txt", "r", stdin);
83     //freopen("CON", "w", stdout);
84     int i, j, k;
85     int test, kase = 1;
86     scanf("%d", &test);
87     while(test--) {
88         int n, q;
89         scanf("%d%d", &n, &q);
90         build(1, n, 1);
91         int x, y, z;
92         while(q--) {
93             scanf("%d%d%d", &x, &y, &z);
94             update(z, x, y, 1);
95         }
96         printf("Case %d: The total value of the hook is %d.
", kase++, SegNode[1].sum);
97     }
98     return 0;
99 }
原文地址:https://www.cnblogs.com/lc520love/p/5311164.html