-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathtrees_with_pointers.cpp
98 lines (79 loc) · 2.24 KB
/
trees_with_pointers.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <vector>
#include <deque>
#include <chrono>
struct node {
node(int k,
node* l = nullptr,
node* r = nullptr)
: key(k), left(l), right(r)
{}
int key;
node* left;
node* right;
};
uint64_t sum(node* n) {
if (n == nullptr) {
return 0;
}
uint64_t left_subtree_sum = 0;
if (n->left != nullptr) {
left_subtree_sum = sum(n->left);
}
uint64_t right_subtree_sum = 0;
if (n->right != nullptr) {
right_subtree_sum = sum(n->right);
}
return n->key + left_subtree_sum + right_subtree_sum;
}
int main() {
std::ios_base::sync_with_stdio(false);
node* root = nullptr;
typedef std::chrono::high_resolution_clock clock_type;
auto start = clock_type::now();
{
std::deque<node*> q;
int n = 0;
std::cin >> n;
for (int i = 0; i < n; ++i) {
int x = 0;
std::cin >> x;
node* n = new node(x);
q.push_back(n);
}
node* last = nullptr;
if (n % 2) {
last = q.back();
q.pop_back();
}
// helper function
auto min_parent = [&](node* left, node* right) {
int min = std::min<int>(left->key, right->key);
node* parent = new node(min, left, right);
q.push_back(parent);
};
// build tree topology
while (q.size() != 1) {
min_parent(q[0], q[1]);
q.pop_front();
q.pop_front();
}
if (last != nullptr) { // create a new root node with
// the old root as left child
// and the last node as right child
min_parent(q.front(), last);
q.pop_front();
}
root = q.front();
}
auto end = clock_type::now();
std::chrono::duration<double> elapsed = end - start;
std::cout << "building took: " << elapsed.count() << " [sec]" << std::endl;
start = clock_type::now();
uint64_t s = sum(root);
end = clock_type::now();
elapsed = end - start;
std::cout << "sum is: " << s << std::endl;
std::cout << "sum took: " << elapsed.count() << " [sec]" << std::endl;
return 0;
}