该程序能统计 input.txt 文件中的所有字符出现的次数,并据此生成各个字符的哈夫曼编码,然后将这些信息写入 output.txt 文件中.(其中 input.txt 文件中的内容只能是键盘上的所有可显示字符和换行符)
#include<iostream>
#include<fstream.h>
#define MAXLEAFNUM 128
typedef struct node//二叉树的结点结构
{
int weight;
char ch;
int parent;
int lchild, rchild;
}Hnode;
typedef char * * HuffmanCode;
HuffmanCode Hc;//用于存储每个字符的哈夫曼编码
Hnode Ht[2 * MAXLEAFNUM];//存储所构造的二叉树
void Select(Hnode Ht[], int n, int &s1, int &s2)
{//在Ht[1..k-1]中选择 parent 为 0 且 weight 最小的两个结点,其序号分别为 s1, s2
int x1 = 32767, x2 = 32767, k;
s1 = s2 = 1;
for(k = 1; k <= n; k++)
{
if((0 == Ht[k].parent) && (Ht[k].weight < x1))
{
x2 = x1;
s2 = s1;
x1 = Ht[k].weight;
s1 = k;
}
else if((0 == Ht[k].parent) && (Ht[k].weight < x2))
{
x2 = Ht[k].weight;
s2 = k;
}
}
}
void CreatHtree(int n, int count[], int &m)//构造一棵含有 n 个树叶的最优二叉