Just a Hook 【线段树】

题目链接HDU-1698

[kuangbin带你飞]专题七 线段树

题目描述

Now Pudge wants to do some operations on the hook.

Let us number the consecutive metallic sticks of the hook from 1 to N. For each operation, Pudge can change the consecutive metallic sticks, numbered from X to Y, into cupreous sticks, silver sticks or golden sticks.
The total value of the hook is calculated as the sum of values of N metallic sticks. More precisely, the value for each kind of stick is calculated as follows:

For each cupreous stick, the value is 1.
For each silver stick, the value is 2.
For each golden stick, the value is 3.

Pudge wants to know the total value of the hook after performing the operations.
You may consider the original hook is made up of cupreous sticks.


思路

区间修改,询问区间和。 典型的线段树板子题;
易错
1.需要用到lazy标记;

代码

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
#include <bits/stdc++.h>
using namespace std;

#define long long long
#define MAX 100010

struct Node{
long l, r, sum, lazy;
void updata(long val)
{
sum = (r - l + 1) * val;
lazy = val;
}
}tree[MAX * 4];

void push_up(int k)
{
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}

void push_down(int k)
{
long lazyval = tree[k].lazy;
if(lazyval)
{
tree[k<<1].updata(lazyval);
tree[k<<1|1].updata(lazyval);
tree[k].lazy = 0;
}
}

void build(int k, int l, int r)
{
tree[k].l = l, tree[k].r = r;
tree[k].sum = tree[k].lazy = 0;
if(l == r)
{
tree[k].sum = 1;
}
else
{
int mid = (l + r) >> 1;
build(k<<1, l, mid);
build(k<<1|1, mid+1, r);
push_up(k);
}
}

void updata(int k, int l, int r, int val)
{
int L = tree[k].l, R = tree[k].r;
if(l <= L && R <= r)
{
tree[k].updata(val);
}
else
{
push_down(k);
int mid = (L + R) >> 1;
if(l <= mid)
updata(k<<1, l, r, val);
if(mid < r)
updata(k<<1|1, l, r, val);
push_up(k);
}
}

int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for(int i = 1; i<=t; i++)
{
int n, m;
cin >> n >> m;
build(1, 1, n);
for(int j = 1; j<=m; j++)
{
int x, y, val;
cin >> x >> y >> val;
updata(1, x, y, val);
}
cout << "Case " << i << ": The total value of the hook is " << tree[1].sum << "." << endl;
}
return 0;
}
-------------本文结束,感谢您的阅读!-------------