-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path757.cpp
More file actions
57 lines (52 loc) · 1.07 KB
/
Copy path757.cpp
File metadata and controls
57 lines (52 loc) · 1.07 KB
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
#include<iostream>
#include<queue>
using namespace std;
struct Node {
int weight;
Node* left = NULL;
Node* right = NULL;
bool isLetter = false;
};
struct compare {
bool operator()(Node* a, const Node* b) {
return a->weight > b->weight;
}
};
int counting(Node* current, int dep) {
int sum = 0;
if (current->isLetter) {
sum += current->weight * dep;
}
if (current->left != NULL) {
sum += counting(current->left, dep + 1);
}
if (current->right != NULL) {
sum += counting(current->right, dep + 1);
}
return sum;
}
int main() {
int n;
while (cin >> n) {
priority_queue<Node*, vector<Node*>, compare> tree;
for (int i = 0; i < n; i++) {
Node* tNode = new Node;
cin >> tNode->weight;
tNode->isLetter = true;
tree.push(tNode);
}
while (tree.size() > 1) {
Node* node1 = tree.top();
tree.pop();
Node* node2 = tree.top();
tree.pop();
Node* Fnode = new Node;
Fnode->weight = node1->weight + node2->weight;
Fnode->left = node1;
Fnode->right = node2;
tree.push(Fnode);
}
cout << counting(tree.top(), 0) << endl;
}
return 0;
}