HDU 1698 Just a Hook(线段树:区间更新)

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

题意:
给出1~n的数,每个数初始为1,每次改变[a,b]的值,最后求1~n的值之和。

 

思路:

区间更新题目,关于懒惰标记什么的参考这个吧http://blog.sina.com.cn/s/blog_a2dce6b30101l8bi.html,讲得不错的。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 const int maxn = 100000 + 10;
 7 
 8 int n, m;
 9 
10 int col[maxn << 2];
11 
12 struct node
13 {
14     int l, r;
15     int n;
16 }t[maxn << 2];
17 
18 //如果该区间被标记了,说明该区间值改变,需要向下传递
19 void PushDown(int o, int m)
20 {
21     if (col[o])
22     {
23         col[o << 1] = col[o << 1 | 1] = col[o];
24         t[o << 1].n = (m - (m >> 1))*col[o];
25         t[o << 1 | 1].n = (m >> 1)*col[o];
26         col[o] = 0;
27     }
28 }
29 
30 void PushUp(int o)
31 {
32     t[o].n = t[o << 1].n + t[o << 1 | 1].n;
33 }
34 
35 void build(int l, int r, int o)
36 {
37     col[o] = 0;
38     t[o].l = l;
39     t[o].r = r;
40     t[o].n = 1;
41     if (l == r) return;
42     int mid = (l + r) / 2;
43     build(l, mid, 2 * o);
44     build(mid + 1, r, 2 * o + 1);
45 }
46 
47 
48 void update(int l, int r, int x, int o)
49 {
50     if (l <= t[o].l && r >= t[o].r)
51     {
52         t[o].n = x*(t[o].r - t[o].l + 1);
53         col[o] = x;
54         return;
55     }
56     PushDown(o, t[o].r - t[o].l +1);
57     int mid = (t[o].l + t[o].r) / 2;
58     if (l > mid)    update(l, r, x, 2 * o + 1);
59     else if (r <= mid)  update(l, r,x, 2 * o);
60     else
61     {
62         update(l, mid, x, 2 * o);
63         update(mid + 1, r, x, 2 * o + 1);
64     }
65     //向上传递
66     PushUp(o);
67 }
68 
69 
70 
71 int main()
72 {
73     //freopen("D:\\txt.txt", "r", stdin);
74     int T;
75     int x, y, k;
76     int kase = 1;
77     scanf("%d", &T);
78     while (T--)
79     {
80         scanf("%d", &n);
81         scanf("%d", &m);
82         build(1, n, 1);
83         for (int i = 1; i <= m; i++)
84         {
85             scanf("%d%d%d", &x, &y, &k);
86             update(x, y, k, 1);
87         }
88         printf("Case %d: The total value of the hook is %d.\n", kase++, t[1].n);
89     }
90 }

 

posted @ 2017-03-15 23:16  Kayden_Cheung  阅读(165)  评论(0编辑  收藏  举报
//目录