#include <iostream>
using namespace std;
struct Haff
{
int weight;
int flag;
int parent;
int left;
int right;
};
#define MAX 65535
Haff haff[20];
void create(int *w,int len,Haff *haff)//
{
int i,j,x1,x2;
int min1,min2;
for(i = 0;i<2*len-1;i++)
{
if(i < len)
{
haff[i].weight = w[i];
}
else
{
haff[i].weight = 0;
}
haff[i].flag = 0;
haff[i].left = 0;
haff[i].right = 0;
haff[i].parent = 0;
}
for(i = 0;i<len-1;i++)
{
min1 = min2 = MAX;
x1 = x2 = 0;
for(j = 0;j<len+i;j++)
{
if(haff[j].weight < min1 && haff[j].flag == 0)
{
min2 = min1;
x2 = x1;
min1 = haff[j].weight;
x1 = j;
}
else if(haff[j].weight < min2 && haff[j].flag == 0)
{
min2 = haff[j].weight;
x2 = j;
}
}
haff[x1].flag = 1;
haff[x2].flag = 1;
haff[x1].parent = len+i;
haff[x2].parent = len+i;
haff[len+i].weight = min1 + min2;
haff[len+i].left = x1;
haff[len+i].right = x2;
}
}
void HaffCode(Haff *pHaffTree,int n,char ***code)
{
int i;
char ch[20]="";
int start = 10;
int Parent;
int Child;
int len;
*code = (char **)malloc(sizeof(char*)*n);
for (i=0;i<n;i++)
{
Parent = pHaffTree[i].parent; //找当前所要进行操作的结点的父结点
Child = i;
start = 10;
while (Parent != 0) //从最下面一直走到根
{
if (pHaffTree[Parent].left == Child)
{
ch[start--] = '0';
}
else
{
ch[start--] = '1';
}
Child = Parent; //当前父节点变成子节点往上继续找父节点
Parent = pHaffTree[Parent].parent;
}
len = strlen(ch+start+1)+1; //计算最后编码的长度
(*code)[i] = (char*)malloc(len);
strcpy((*code)[i],ch+start+1);
}
}