-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhwheap1.cpp
More file actions
99 lines (76 loc) · 1.48 KB
/
hwheap1.cpp
File metadata and controls
99 lines (76 loc) · 1.48 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
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
99
#include <iostream>
#include <vector>
using namespace std;
void heap_shift_up(vector<int> &heap, int i)
{
while (i > 0)
{
int p = (i - 1) / 2;
if (heap[i] >= heap[p])
return;
swap(heap[i], heap[p]);
i = p;
}
}
void heap_shift_dwn(vector<int> &heap, int i)
{
int n = heap.size();
while (true)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int min = i;
if (l < n && heap[l] < heap[min])
min = l;
if (r < n && heap[r] < heap[min])
min = r;
if (min != i)
{
swap(heap[i], heap[min]);
i = min;
}
else
break;
}
}
void push_heap(vector<int> &heap, int x)
{
heap.push_back(x);
heap_shift_up(heap, heap.size() - 1);
}
void pop_heap(vector<int> &heap)
{
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty())
heap_shift_dwn(heap, 0);
}
void make_heap(vector<int> &heap)
{
for (int i = heap.size() / 2 - 1; i >= 0; --i)
heap_shift_dwn(heap, i);
}
int main()
{
int n;
cin >> n;
vector<int> heap;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
push_heap(heap, x);
}
int result = 0;
while (heap.size() > 1)
{
int a = heap[0];
pop_heap(heap);
int b = heap[0];
pop_heap(heap);
int s = a + b;
result += s;
push_heap(heap, s);
}
cout << result;
}