0%

使用贪心算法构造 Huffman tree

以下代码是使用贪心算法,构造huffman树的C++实现代码。
来源于我的算法课程实验。

Test Case 测试用例

5
a 0.12
b 0.40
c 0.15
d 0.08
e 0.25

Code 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include<iostream>
#include<string>
#define MAXN 10000
#define INF 10000000000
using namespace std;

typedef struct node{
char c;
string code;
double weight;
int left_child;
int right_child;
int parent;
} ;

node pool [MAXN];

int count;
int index;

void init(){
index = count;
for( int i = 0 ; i < MAXN ; i ++ ){
pool[i].c = '\0';
pool[i].left_child = -1;
pool[i].parent = -1;
pool[i].right_child = -1;
}
}

void input(){
cout<<"请依次输入元素和权值,如 a 3"<<endl;
for( int i = 0 ; i < count ; i ++){
cin>>pool[i].c;
cin>>pool[i].weight;
}
}

void solve(){
int elements_max_number = (count *2 - 1);
while(index < elements_max_number){
int min_index_1 = -1;
int min_index_2 = -1;
double min_sum = INF;
for( int index_1 = 0 ; index_1<index ; index_1 ++){
if(pool[index_1].parent == -1){
for(int index_2 = 0; index_2 < index ; index_2 ++){
if(index_1 != index_2 && pool[index_2].parent == -1){
if((pool[index_1].weight+pool[index_2].weight)<min_sum){
min_index_1 = index_1;
min_index_2 = index_2;
min_sum = pool[index_1].weight+pool[index_2].weight;
}
}
}
}
}
pool[index].c = '\0';
pool[index].left_child = min_index_1;
pool[index].right_child= min_index_2;
pool[index].parent = -1;
pool[index].weight = min_sum;
pool[min_index_1].parent = index;
pool[min_index_2].parent = index;
index ++;
}
}

void coding(int flag){
if(flag == (count * 2 - 2 )){
pool[flag].code = "";
coding(pool[flag].left_child);
coding(pool[flag].right_child);
}else if(flag != -1){
int parent = pool[flag].parent;
if(flag==pool[parent].left_child){
pool[flag].code = pool[parent].code+"0";
}else{
pool[flag].code = pool[parent].code+"1";
}
coding(pool[flag].left_child);
coding(pool[flag].right_child);
}
}

int main(){
cout<<"请输入元素个数: ";
cin>>count;
if(count && count < MAXN / 2 ){
init();
input();
solve();
coding(count*2-2);
system("cls");
cout<<"---------- HaffMan Code Result ----------"<<endl;
for(int i = 0 ; i < count ; i ++){
cout<<"Key : "<<pool[i].c<<"\tHaffman Code:"<<pool[i].code<<endl;
}
}else{
cout<<"Err..."<<endl;
}
return 0;
}