#define _CRT_SECURE_NO_WARNINGS #include <iostream> //#pragma warning(disable:4996) using namespace std; typedef char **HuffmanCode; typedef struct{ int weight; int parent, lchild, rchild; }HTNode, *HuffmanTree; void Select(HuffmanTree HT, int n, int &s1, int &s2) { int min1 = 100000, min2 = min1; for (int i = 1; i <= n; i++) { if (HT[i].weight <= min1 && HT[i].parent == 0) { min1 = HT[i].weight; s1 = i; } } HT[s1].parent = -1; for (int i = 1; i <= n; i++) { if (HT[i].weight <= min2 && HT[i].parent == 0) { min2 = HT[i].weight; s2 = i; } } } void CreatHuffmanTree(HuffmanTree &HT, int n) { if (n <= 1) return; int m = 2 * n - 1, s1, s2; HT = new HTNode[m + 1]; for (int i = 1; i <= m; ++i) { HT[i].lchild = 0; HT[i].rchild = 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 = HT[s2].parent = i; HT[i].lchild = s1; HT[i].rchild = s2; HT[i].weight = HT[s1].weight + HT[s2].weight; } } void CreatHuffmanCode(HuffmanTree HT, HuffmanCode &HC, int n) { HC = new char*[n + 1]; char *cd= new char[n]; cd[n - 1] = '\0'; for (int i = 1; i <= n; ++i) { int start = n - 1, c = i, f = HT[i].parent; while (f != 0) { --start; if (HT[f].lchild == c) cd[start] = '0'; else cd[start] = '1'; c = f; f = HT[f].parent; } HC[i] = new char[n - start]; strcpy(HC[i], &cd[start]); } delete[] cd; } int main() { int n; HuffmanTree HT; HuffmanCode HC; cout << "根据n个权值{ W1,W2....Wn }构造哈夫曼树.\n"; cout << "输入权值个数n: "; cin >> n; cout << "输入n个权值:"; CreatHuffmanTree(HT, n); CreatHuffmanCode(HT, HC, n); cout << "这n个权值的哈夫曼编码为:\n"; for (int i = 1; i <= n; i++) cout << HC[i] << endl; return 0; }
运行结果: