-
Notifications
You must be signed in to change notification settings - Fork 2
/
segment tree.txt
63 lines (53 loc) · 1.36 KB
/
segment tree.txt
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
//segment tree for maximum value
void build(ll tree[],ll a[],ll node, ll start, ll end)
{
if(start == end)
{
tree[node] = a[start];
}
else
{
ll mid = (start + end) / 2;
build(tree,a,(2*node)+1, start, mid);
build(tree,a,(2*node)+2, mid+1, end);
tree[node] = max(tree[(2*node)+1],tree[(2*node)+2]);
}
}
void update(ll tree[],ll a[],ll node, ll start, ll end, ll idx, ll val)
{
if(start == end)
{
a[idx] = val;
tree[node] = val;
}
else
{
ll mid = (start + end) / 2;
if(start <= idx && idx <= mid)
{
update(tree,a,(2*node)+1, start, mid, idx, val);
}
else
{
update(tree,a,(2*node)+2, mid+1, end, idx, val);
}
tree[node] = max(tree[(2*node)+1],tree[(2*node)+2]);;
}
}
ll query(ll tree[],ll node, ll start, ll end, ll l, ll r)
{
if(r < start || end < l)
{
return 0;
}
if(l <= start && end <= r)
{
// range of node completely inside given range
return tree[node];
}
// range represented by a node is partially inside and partially outside the given range
ll mid = (start + end) / 2;
ll p1 = query(tree,(2*node)+1, start, mid, l, r);
ll p2 = query(tree,(2*node)+2, mid+1, end, l, r);
return max(p1,p2);
}