一、问题描述
给定n个权值作为n个叶子结点,构造一棵二叉树,若带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树
二、哈夫曼树的建立
(1)初始化:根据给定的n个权值,构造n棵二叉树的森林集合F={T1,T2,…,Tn},其中每棵二叉树只有一个权值为Wi的根节点,左右子树均为空。
(2)找最小的树并构造新的树:在森林集合F中选取两颗根的权值最小的树作为左右子树构造一棵新的二叉树,新二叉树的根结点为新增加的结点,其权值为左右子树根的权值之和。
(3)删除与插入:在森林集合中删除已选取的两棵根的权值最小的树,同时将新构造的二叉树加入到森林集合F中。
(4)重复(2)和(3)步骤:直到森林集合只含有一棵树为止,这棵树即为哈夫曼树。
三、代码
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct Tree {
int weight;
char name;
Tree *Left, *Right;
};
string code[22];//记录编码结果
int ans;
string s = "abcdefghijklmnopqrstvwxyz";//方便输出结果
struct cmp {
bool operator()(const Tree T1, const Tree T2) {
return T1.weight >= T2.weight;
}
};
priority_queue<Tree, vector<Tree>, cmp> q;
string Code;
void dfs(Tree *t) {
if (!t->Left && !t->Right)
{
code[t->name - 'a'] = Code;
return;
}
Code.push_back('0');
dfs(t->Left);
Code.pop_back();
Code.push_back('1');
dfs(t->Right);
Code.pop_back();
}
int main() {
int n, W[22];
string str;
cin >> n >> str;
for (int i = 0; i < n; i++) {
cin >> W[i], q.push({ W[i],str[i],NULL,NULL });
}
Tree *L, *R, *T;
Tree a, b;
while (!q.empty()) {
a = q.top(), q.pop();
L = new Tree();
L->weight = a.weight, L->name = a.name;
L->Left = a.Left, L->Right = a.Right;
if (!q.empty()) {
b = q.top(), q.pop();
R = new Tree();
R->weight = b.weight, R->name = b.name;
R->Left = b.Left, R->Right = b.Right;
}
else
break;
ans = ans + a.weight + b.weight;
q.push({ a.weight + b.weight, '-', L, R });
}
T = L;
dfs(T);
cout <<ans << endl;
for (int i = 0; i < n; i++) {
cout << s[i] << ':' << code[i] << endl;
}
return 0;
}