-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9_MinWeightPathLen.cpp
More file actions
51 lines (45 loc) · 931 Bytes
/
9_MinWeightPathLen.cpp
File metadata and controls
51 lines (45 loc) · 931 Bytes
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
/**
* P344 哈夫曼树
* 优先队列 小根堆
*/
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
// 小根堆
priority_queue<int, vector<int>, greater<int>> small_heap;
void init()
{
int num;
cout << "Input the number of nodes: ";
cin >> num;
// 初始化优先队列 小根堆
for (int i = 0; i < num; i++)
{
int newVal;
cin >> newVal;
small_heap.push(newVal);
}
}
int getMinWeightPath()
{
int result = 0;
while (small_heap.size() >= 2)
{
// 取出最小的两个元素
int a = small_heap.top();
small_heap.pop();
int b = small_heap.top();
small_heap.pop();
small_heap.push(a + b);
result += a + b;
}
return result;
}
int main()
{
init();
int result = getMinWeightPath();
cout << "Minimum weight path length is: " << result << endl;
return 0;
}