-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLista4B.cpp
More file actions
113 lines (93 loc) · 2.34 KB
/
Lista4B.cpp
File metadata and controls
113 lines (93 loc) · 2.34 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#define endl "\n"
using namespace std;
int remove(int* hp, int n);
void HeapBottomUp(int* array, int n);
void Heapsort(int* hp, int n);
void PrintHeap(int* hp, int n);
int Sum(int* hp, int n);
int main(void) {
int n;
while(n != 0) {
cin >> n;
if(n == 0) {
break;
}
int hp[n+1];
for(int i = 1; i <= n; i++) {
cin >> hp[i];
}
HeapBottomUp(hp, n);
cout << Sum(hp, n) << endl;
}
return 0;
}
int remove(int* hp, int n) {
if(n > 0 && hp != NULL) {
int tmp;
tmp = hp[1];
hp[1] = hp[n];
hp[n] = tmp;
n--;
HeapBottomUp(hp, n);
return tmp;
}
return -1;
}
void HeapBottomUp(int* array, int n) {
for(int i = (n / 2); i >= 1; i--) {
int k = i; // current position of the i-th internal node
int v = array[k]; // value of the i-th internal node
bool heap = false;
// finding the proper place for the i-th internal node
while(heap == false && 2*k <= n) {
int j = 2*k; // position of the first child
if(j < n) { // has two children | finds the shortest child
if(array[j] > array[j+1]) {
j = j + 1;
}
}
if(v < array[j]) { // is a heap if v is < than the shortest child
heap = true;
}
else { // places the shortest child in H[k] | updates k
array[k] = array[j];
k = j;
}
}
array[k] = v;
}
}
void Heapsort(int* hp, int n) { // for min heap
int aux[n];
int tam = n;
for(int i = 0; i < n; i++) {
aux[i] = remove(hp, tam);
tam--;
if(tam > 0) {
PrintHeap(hp, tam);
}
}
for(int i = 0; i < n; i++) {
cout << aux[i] << " ";
}
cout << endl;
}
int Sum(int* hp, int n) {
int cost = 0;
int size = n;
for(int i = n; i > 1; i--) {
int min = remove(hp, size);
size--;
hp[1] = min + hp[1];
cost = hp[1] + cost;
HeapBottomUp(hp, size);
}
return cost;
}
void PrintHeap(int* hp, int n) {
for(int i = 1; i <= n; i++) {
cout << hp[i] << " ";
}
cout << endl;
}