哈夫曼树,第一行输入一个数n,表示叶结点的个数。
需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出哈夫曼树的带权路径长度(WPL)。
输入格式:
第一行输入一个数n,第二行输入n个叶结点(叶结点权值不超过1000,2<=n<=1000)。
输出格式:
在一行中输出WPL值。
输入样例:
5
1 2 2 5 9
输出样例:
37
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MINDATA -1
typedef struct HNode* Heap;
typedef Heap MinHeap;
struct HNode {
int* Data;
int Size;
};
MinHeap CreateHeap(int MaxSize) {
MinHeap H = (MinHeap)malloc(sizeof(struct HNode));
H->Data = (int*)malloc((MaxSize + 1) * sizeof(int));
H->Size = 0;
H->Data[0] = MINDATA;
return H;
}
void Insert(MinHeap H, int X) {
int i;
i = ++H->Size;
for (; H->Data[i / 2] > X; i /= 2)
H->Data[i] = H->Data[i / 2];
H->Data[i] = X;
}
int DeleatMin(MinHeap H) {
int Parent, Child;
int MinItem, X;
MinItem = H->Data[1];
X = H->Data[H->Size--];
for (Parent = 1; Parent * 2 <= H->Size; Parent = Child){
Child = Parent * 2;
if ((Child != H->Size) && (H->Data[Child]>H->Data[Child+1]))
Child++;
if (X <= H->Data[Child])break;
else
H->Data[Parent] = H->Data[Child];
}
H->Data[Parent] = X;
return MinItem;
}
int main() {
int n, x, a, b, sum = 0;
scanf("%d", &n);
Heap H = CreateHeap(n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
Insert(H, x);
}
while (H->Size != 1) {
a = DeleatMin(H);
b = DeleatMin(H);
b = a + b;
sum += b;
Insert(H, b);
}
printf("%d", sum);
system("pause");
return 0;
}