#include"iostream"
#define n 8
using namespace std;
//如何·建立哈夫曼树是一大·难点
typedef struct
{
int weight;
int parent, lchild, rchild;
}HTNode, *HuffmanTree;
//初始化数组
void Initial_HT(HTNode a[])
{
for (int i = 1; i < 2 * n; i++){
a[i].weight = a[i].parent = a[i].lchild = a[i].rchild = 0;
}
}
//挑选其中两个权值最小的
void Select_HT(HTNode a[], int K, int &M, int &N)
{
int min = a[1].weight;
int i = 1;
for (; i < K; i++){
if (min>=a[i].weight&&a[i].parent == 0)
min = a[i].weight;
}
M = i;
cout << i << endl;;
int min2 = a[1].weight;
int j = 1;
for (; j < K+1; j++){
if (min2>a[j].weight&&a[j].weight != min&&a[i].parent == 0)
min2 = a[j].weight;
}
N = j;
}
//创建一哈夫曼树
void Create_HT(HTNode a[])
{
cout << "输进叶子结点的权值:" << endl;
for (int i = 1; i < n + 1; i++){
cin >> a[i].weight;
}
int M = 0, N = 0;
for (int j = n + 1; j < 2 * n + 1; j++){
Select_HT(a, j - 1, M, N);//其作用将实现的功能有返回最小的两个下标//忘了除去已有的父母的结点了
a[M].parent = a[N].parent = j;
a[N + 1].lchild = M;
a[N + 1].rchild = N;
a[j].weight = a[N].weight + a[M].weight;
}
}
void Print_HT(HTNode a[])
{
for (int i = 1; i < 2 * n; i++){
cout << a[i].weight;
}
}
int main()
{
HTNode a[2 * n];
Initial_HT(a);
Create_HT(a);
Print_HT(a);
return 0;
}