-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree.cpp
73 lines (64 loc) · 1.15 KB
/
binary_tree.cpp
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
//
// binary tree (for finding max)
// by Zosia @ 2024/09/22
//
#include <iostream>
using namespace std;
const int N = 1e6 + 21;
int n, base = 1;
int tab[N];
int tree[2*N];
void build_tree() // building tree, run once - O(n)
{
for (int i=0; i<n; i++)
{
tree[i+base] = tab[i];
}
for (int i=n-1; i>0; i--)
{
tree[i] = max(tree[2*i], tree[2*i+1]);
}
}
void change_value(int k, int v) // changing element value at position k to v - O(log(n))
{
tree[k+base] = v;
int index = (k+base)/2;
while (index >= 1)
{
tree[index] = max(tree[2*index], tree[2*index+1]);
index /= 2;
}
}
int find_max()
{
return tree[1];
}
void display_tree()
{
int power = 2;
for (int i=1; i<2*n; i++)
{
if (power == i)
{
cout<<endl;
power *= 2;
}
cout<<tree[i]<<" ";
}
cout<<endl;
}
int main()
{
// input
cin>>n;
for (int i=0; i<n; i++)
cin>>tab[i];
// finding base
while (base < n)
base *= 2;
build_tree();
display_tree();
change_value(1, 1);
display_tree();
cout<<find_max()<<endl;
}