File size: 696 Bytes
3805fe5 bff4ec7 3805fe5 bff4ec7 | 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 | int huffman_cost(int *weights, int n)
{
int work[8];
for (int i = 0; i < n; ++i) {
work[i] = weights[i];
}
int active = n;
int total = 0;
while (active > 1) {
int first = 0;
for (int i = 1; i < active; ++i) {
if (work[i] < work[first]) {
first = i;
}
}
int x = work[first];
--active;
work[first] = work[active];
int second = 0;
for (int i = 1; i < active; ++i) {
if (work[i] < work[second]) {
second = i;
}
}
int y = work[second];
--active;
work[second] = work[active];
int merged = x + y;
total += merged;
work[active] = merged;
++active;
}
return total;
}
|