1.代码
#include<iostream>
#include<cstring>
using namespace std;
//const int N=1e4;
/*typedef struct PTNode{
char data;
int parent;
}PTNode;
typedef struct {
PTNode nodes[N];
int r,n;
}PTree;
//双亲表示法
typedef struct CTNode{
int child;
struct CTNode *next;
}*ChildPtr;
typedef struct{
char data;
ChildPtr linklist;
}CTBox;
typedef struct {
CTBox nodes[N];
int r,n;
}CTree;
//孩子表示法
typedef struct CSNode{
char data;
struct CSNode *kid,*bro;
};*/
//孩子兄弟表示法
/*哈夫曼树(最优树)
本质:最小带权路径(权越大离根越近)
贪心算法
如何构造哈夫曼树
1.构造森林 2.选用两个权值最小的树作为叶子节点构造二叉树 3.删除已选的树 4.重复2和3,直到树森林里只有一棵树
特点:1.哈夫曼树的结点的度数要么为0要么为2,不可能为1
2.哈夫曼树有n个叶子结点,一定有2*n-1个结点
3.n棵树需要经历n-1次合并,产生n-1个新节点
*/
typedef struct{
int parent,lch,rch;
int weight;
}HTNode,*HuffmanTree;
typedef char** HuffmanCode;
void Select(HuffmanTree& HT, int n, int& s1, int& s2)
{
int min=0;
for (int i=1;i<=n;i++)
{
if (HT[i].parent==0)
{
min=i;
break;
}
}
for (int i=min+1; i<=n; i++)
{
if (HT[i].parent==0&&HT[i].weight < HT[min].weight)
min=i;
}
s1=min; //第一个最小值给s1
for (int i=1; i<=n;i++)
{
if (HT[i].parent==0&&i!=s1)
{
min=i;
break;
}
}
for (int i=min+1; i<=n;i++)
{
if (HT[i].parent==0&&HT[i].weight<HT[min].weight&&i!=s1)
min=i;
}
s2=min;
}
void CreatHuffmanTree(int n,HuffmanTree& HT) {
if (n <= 1)
return;
int s1, s2;
int m = 2*n-1;
HT = new HTNode[m+1];
for (int i=1;i<=m;i++) {
HT[i].lch=0;
HT[i].rch=0;
HT[i].parent=0;
}
for (int i=1; i<=n;i++) {
cin>>HT[i].weight;
}
for (int i=n+1;i<=m;i++) {
Select(HT, i - 1, s1, s2);
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].weight = HT[s1].weight + HT[s2].weight;
HT[i].lch = s1;
HT[i].rch = s2;
}
printf("哈夫曼树为:>\n");
printf("下标 权值 父结点 左孩子 右孩子\n");
printf("0 \n");
for (int i = 1; i <= m; i++) {
printf("%-4d %-6d %-6d %-6d %-6d\n", i, HT[i].weight, HT[i].parent, HT[i].lch, HT[i].rch);
}
printf("\n");
}
void CreatHuffmanCode(int n,HuffmanTree HT,HuffmanCode& HC){
HC=new char*[n+1];
char* code=new char[n];
code[n-1]='\0';
for(int i=1;i<=n;i++){
int start=n-1;
int c=i;
int p=HT[i].parent;
while(p){
if(HT[p].lch==c){
code[--start]='0';
}
else{
code[--start]='1';
}
c=p;
p=HT[p].parent;
}
HC[i]=new char[n-start];
strcpy(HC[i],&code[start]);
}
delete []code;
}
int main(){
HuffmanTree HT;
HuffmanCode HC;
int n;
cin>>n;
CreatHuffmanTree(n,HT);
CreatHuffmanCode(n,HT,HC);
printf("\n");
for(int i=1;i<=n;i++){
printf("%s\n",HC[i]);
}
return 0;
}