1 #include <iostream>
2 #include <string.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5
6
7 using namespace std;
8 /*
9 1. 哈夫曼编码-顺序存储方式
10 2. 优先队列存储——堆存储
11 */
12
13 void huffmanTree(int huffman[][5],int n)
14 {
15
16 for (int i=0;i<n;i++)
17 {
18 huffman[i][0] = i;
19 cin >> huffman[i][1];
20 huffman[i][2] = -1;
21 huffman[i][3] = -1;
22 huffman[i][4] = -1;
23 }
24 int num1 = 0,num2 = 0;
25 float min1 = 9999,min2 = 9999;
26
27 for (int i=0;i<n-1;i++)
28 {
29 num1 = 0;
30 num2 = 0;
31 min1 = 9999;
32 min2 = 9999;
33 for (int j=0;j<n+i;j++)
34 {
35 // 找到一组数中未被排序(没有父节点)的的最小值和次小值,最小值优先判断,判断完最小值后判断次小值
36 if (huffman[j][2] == -1 && huffman[j][1] < min1 )
37 {
38 if (min1 < min2)
39 {
40 min2 = min1;
41 num2 = num1;
42 }
43 min1 = huffman[j][1];
44 num1 = j;
45 }
46 else if (huffman[j][2] == -1 && huffman[j][1] < min2)
47 {
48 min2 = huffman[j][1];
49 num2 = j;
50 }
51 }
52 huffman[n+i][0] = n+i;
53 huffman[n+i][1] = huffman[num1][1]+huffman[num2][1];
54 huffman[n+i][2] = -1;
55 huffman[n+i][3] = num1;
56 huffman[n+i][4] = num2;
57 huffman[num1][2] = n+i;
58 huffman[num2][2] = n+i;
59
60 }
61 }
62 void printTree(int huffman[][5],int n)
63 {
64 for (int i=0;i<2*n-1;i++)
65 {
66 for (int j=0;j<5;j++)
67 cout << huffman[i][j] << ' ';
68 cout << endl;
69 }
70 }
71 void huffmanCode(int huffman[][5],int n)
72 {
73 // 自顶向下法:找到根到所有孩子的路径,每条路径均对应一个孩子
74 // 自底向上法:遍历每个叶子结点,往上寻找直到找到根为止
75 char code[20];
76 int q,parent;
77 int j = 0;
78 for (int i=0;i<n;i++)
79 {
80 q = i;
81 parent = huffman[q][2];
82 j = 0;
83 while (parent!=-1)
84 {
85 if (huffman[parent][3] == q)
86 {
87 // q是parent的左孩子
88 code[j] = '0';
89 }
90 if (huffman[parent][4] == q)
91 {
92 code[j] = '1';
93 }
94 j++;
95 q = parent;
96 parent = huffman[q][2];
97 }
98 code[j] = '