//创建日期2017.2.22
//哈夫曼树
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct
{
int data;
int parent;
int leftChild, rightChild;
}node;//data是数值、其他的存数组下标
node *treee;
int Huffman(int *a, int n)
{
int ans = 0;
node tree[200];//数组+指针,十字链表法?!
int m = 2 * n - 1; //节点总数
for (int i = 0; i < n; i++)
tree[i].data = a[i];
for (int i = 0; i < m; i++) //初始化每个节点
{
tree[i].parent = NULL;
tree[i].leftChild = NULL;
tree[i].rightChild = NULL;
}
for (int i = n; i < m; i++) //非叶子节点
{
int min1 = 1000000, min2 = 1000000;
int pos1=0, pos2=0; //第一小和第二小
for (int j = 0; j < i; j++) //叶子节点
{
if (tree[j].parent == NULL)//还没进构成树的结点
{
if (tree[j].data < min1)
{
//swap();
pos2 = pos1;
pos1 = j;
min2 = min1;
min1 = tree[j].data;
}
else if (tree[j].data < min2)
{
min2 = tree[j].data;
pos2 = j;
}
}
}
tree[i].leftChild = min(pos1, pos2);
tree[i].rightChild = max(pos1, pos2);
tree[i].data = tree[pos1].data + tree[pos2].data;
tree[pos1].parent = i;
tree[pos2].parent = i;
ans += tree[i].data;
}
treee = tree;//为了把构造好的哈夫曼树用全局变量传递出来
return ans;//哈夫曼树最小权值
}
int main()
{
int num[120];
int n;
cout << "比如:用5个带权值{3,2,4,5,1}构造的哈夫曼树的带权路径长度" << endl;
//n个数字,排列出哈夫曼树
cout << "请输入要输入的元素的个数" << endl;
cin >> n;
cout << "请输入各个元素的值(非负数)" << endl;
for (int i = 0; i < n; i++)
cin >> num[i];
cout << "所得结果:"<<Huffman(num, n) << endl;
}