一、问题
二、解析
哈夫曼树构造:
- 根据给定的n个权值{w1,w2,…,wn}构成二叉树集合F={T1,T2,…,Tn},其中每棵二叉树Ti中只有一个带权为wi的根结点,其左右子树为空.
- 在F中选取两棵根结点权值最小的树作为左右子树构造一棵新的二叉树,且置新的二叉树的根结点的权值为左右子树根结点的权值之和.
- 在F中删除这两棵树,同时将新的二叉树加入F中.
- 重复2、3,直到F只含有一棵树为止.(得到哈夫曼树)
三、设计
void SetHuffTree(node HuffTree[],int w[] , char ch[], int n)
{
for (int i = 0; i < 2 * n - 1; ++i)
{
HuffTree[i].parent = -1;
HuffTree[i].lchild = -1;
HuffTree[i].rchild = -1;
}
for (int i = 0; i < n; ++i)
{
HuffTree[i].weight = w[i];
HuffTree[i].ch = ch[i];
}
for (int i = n; i < 2 * n - 1; ++i)
{
int a = 0, b = 0;
select(HuffTree, &a, &b, i);
HuffTree[a].parent = i;
HuffTree[b].parent = i;
HuffTree[i].weight = HuffTree[a].weight + HuffTree[b].weight;
HuffTree[i].lchild = a;
HuffTree[i].rchild = b;
}
}
四、分析
时间复杂度为O(n^2)
五、代码
#include<iostream>
#include<vector>
#include<cmath>
#include<time.h>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 2e5 + 10;
const int inf = 0x3f3f3f3f;
int n;
struct node
{
int weight;
char ch;
int lchild, rchild, parent;
}HuffTree[maxn * 2];
int w[maxn];
char ch[maxn];
void select(node HuffTree[], int* a, int *b , int n)
{
int weight = inf;
for (int i = 0; i < n; ++i)
{
if (HuffTree[i].parent != -1)
continue;
else
{
if (HuffTree[i].weight < weight)
{
weight = HuffTree[i].weight;
*a = i;
}
}
}
weight = inf;
for (int i = 0; i < n; ++i)
{
if (HuffTree[i].parent != -1 || i == *a)
continue;
else
{
if (HuffTree[i].weight < weight)
{
weight = HuffTree[i].weight;
*b = i;
}
}
}
int temp;
if (HuffTree[*a].lchild < HuffTree[*b].lchild)
{
temp = *a;
*a = *b;
*b = temp;
//swap(*a, *b);
}
}
void SetHuffTree(node HuffTree[],int w[] , char ch[], int n)
{
for (int i = 0; i < 2 * n - 1; ++i)
{
HuffTree[i].parent = -1;
HuffTree[i].lchild = -1;
HuffTree[i].rchild = -1;
}
for (int i = 0; i < n; ++i)
{
HuffTree[i].weight = w[i];
HuffTree[i].ch = ch[i];
}
for (int i = n; i < 2 * n - 1; ++i)
{
int a = 0, b = 0;
select(HuffTree, &a, &b, i);
HuffTree[a].parent = i;
HuffTree[b].parent = i;
HuffTree[i].weight = HuffTree[a].weight + HuffTree[b].weight;
HuffTree[i].lchild = a;
HuffTree[i].rchild = b;
}
}
void SetHuffCode(node HuffTree[], int n)
{
string s = "";
for (int i = 0; i < n; ++i)
{
s = "";
int j = i;
while (HuffTree[j].parent != -1)
{
int k = HuffTree[j].parent;
if (j == HuffTree[k].lchild)
{
s += "0";
}
else
{
s += "1";
}
j = HuffTree[j].parent;
}
cout << "字符" << HuffTree[i].ch << "的编码" << endl;
for (int i = s.size() - 1; i >= 0; --i)
{
cout << s.at(i);
}
cout << endl;
}
}
int main()
{
scanf("%d", &n);
scanf("%s", ch);
for (int i = 0; i < n; ++i)
{
scanf("%d", &w[i]);
}
SetHuffTree(HuffTree, w, ch , n);
SetHuffCode(HuffTree, n);
return 0;
}