创建哈夫曼树
#include <iostream>
#pragma warning(disable:4996)
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
typedef int MyWeight;
typedef char MyDataType;
typedef char** HuffmanCode;
typedef struct HuffmanTrees {
MyWeight weight;
int parent, lch, rch;
MyDataType cc;
}*HuffmanTree;
void Select(HuffmanTree& ht, int a, int& num1, int& num2) {
int min;
for (int i = 1; i <= a; ++i) {
if (ht[i].parent == 0) {
min = ht[i].weight; break;
}
}
for (int i = 1; i <= a; ++i) {
if (ht[i].parent == 0 && ht[i].weight <= min) {
min = ht[i].weight; num1 = i;
}
}
for (int i = 1; i <= a; ++i) {
if (ht[i].parent == 0 && i != num1) {
min = ht[i].weight; break;
}
}
for (int i = 1; i <= a; ++i) {
if (ht[i].parent == 0 && ht[i].weight <= min && i != num1) {
min = ht[i].weight; num2 = i;
}
}
}
int CreateHuffmanTree(HuffmanTree& ht, int n) {
if (n <= 1)return ERROR;
int m = 2 * n - 1;
ht = new HuffmanTrees[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) {
int s1, s2;
Select(ht, i - 1, s1, s2);
ht[s1].parent = i; ht[s2].parent = i;
ht[i].lch = s1; ht[i].rch = s2; ht[i].weight = ht[s1].weight + ht[s2].weight;
}
return OK;
}
void CreateHuffmanCode(HuffmanTree& ht, HuffmanCode& hc, int n) {
hc = new char* [n + 1];
char* chars = new char[n];
chars[n - 1] = '\n';
for (int i = 1; i <= n; ++i) {
int storeLabel = n - 1; int count = i; int fm = ht[i].parent;
while (fm != 0) {
--storeLabel;
if (ht[fm].lch == count) chars[storeLabel] = '0';
else chars[storeLabel] = '1';
count = fm;
fm = ht[fm].parent;
}
hc[i] = new char[n - storeLabel];
strcpy(hc[i], &chars[storeLabel]);
}
delete[] chars;
chars = NULL;
}
int main()
{
HuffmanTree HT;
int k; cin >> k;
CreateHuffmanTree(HT, k);
HuffmanCode HC;
CreateHuffmanCode(HT, HC, k);
for (int i = 1; i <= k; ++i) {
cout << HC[i] << endl;
}
}
