哈夫曼树:

带权路径长度(WPL)最小的树,最优前缀树(任何一个编码都不是另一个编码的前缀)

当有n个叶子节点时,共有2n-1个,因为哈夫曼树的节点只有度为0和2(参考二叉树节点计算)

构造:

在森林中,每次选取最小的两个节点合成树,直至最后只有一棵树

以下用哈夫曼编码压缩普通文件

这里不要用流进行读写,因为流会受分隔符的影响

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <bitset>
#include <memory>
#include <string>
#include <sstream>
#include <fstream>
#include <sys/stat.h>
#include <cstring>

class HuffmanTree
{
private:
struct Node
{
int weight;
char c;
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
Node(int w) : weight(w), left(nullptr), right(nullptr) {}
};
using Htree = std::shared_ptr<Node>;
Htree root;
std::unordered_map<char, std::string> code;
std::unordered_map<std::string, char> recode;
std::unordered_map<char, int> weight;
std::string filename;

public:
HuffmanTree(const std::string& file) : root(nullptr), filename(file) {}
void readFile()
{
std::ifstream in(filename);
if (!in)
{
std::cout << "open file failed" << std::endl;
return;
}
char c;
while (in.get(c))
{
weight[c]++;
}
in.close();
}

void create_HuffmanTree()
{
auto cmp = [](auto &lhs, auto &rhs)
{ return lhs->weight > rhs->weight; };

std::priority_queue<Htree, std::vector<Htree>, decltype(cmp)> pq(cmp);
for (auto &p : weight)
{
Htree node = std::make_shared<Node>(p.second);
node->c = p.first;
pq.push(node);
}

while (pq.size() > 1)
{
Htree left = pq.top();
pq.pop();
Htree right = pq.top();
pq.pop();
Htree parent = std::make_shared<Node>(left->weight + right->weight);
parent->left = left;
parent->right = right;
pq.push(parent);
}
root = pq.top();
}

void Hcode(std::string path, const Htree& root)
{
if (!root->left && !root->right)
{
code[root->c] = path;
recode[path] = root->c;
return;
}
if (root->left)
Hcode(path + "0", root->left);
if (root->right)
Hcode(path + "1", root->right);
}

void printCode()
{
for (auto &p : code)
{
std::cout << p.first << " " << p.second << std::endl;
}
}

const Htree &gettree() const
{
return root;
}

void encode()
{
std::ifstream in(filename, std::ios::binary|std::ios::in);
if(!in)
{
std::cerr << "open file failed" << std::endl;
return;
}
char c;
std::string stream;
while (in.get(c))
{
stream += code[c];
}
in.close();

std::ofstream out(filename + ".huf", std::ios::binary|std::ios::out);
if(!out)
{
std::cerr << "open file failed" << std::endl;
return;
}

uint32_t map_size = recode.size();
out.write(reinterpret_cast<const char*>(&map_size), sizeof(map_size));
uint32_t bit_size = stream.size();
out.write(reinterpret_cast<const char*>(&bit_size), sizeof(bit_size));
for(auto &p : recode)
{
uint32_t key_size = p.first.size();
out.write(reinterpret_cast<const char*>(&key_size), sizeof(key_size));
out.write(reinterpret_cast<const char*>(p.first.data()), key_size);
out.write(reinterpret_cast<const char*>(&p.second), sizeof(p.second));
}


for (int i = 0; i < stream.size(); i += 8)
{
std::string tmp = stream.substr(i, 8);
while (tmp.length() < 8)
tmp += "0";
std::bitset<8> bs(tmp);
uint8_t byte = bs.to_ulong();
out.write(reinterpret_cast<const char*>(&byte), sizeof(byte));
}
out.close();
}

void decode()
{
std::ifstream in(filename+".huf", std::ios::binary|std::ios::in);
if(!in)
{
std::cerr << "open file failed" << std::endl;
return;
}
std::unordered_map<std::string, char> code;

uint32_t size;
in.read(reinterpret_cast<char*>(&size), sizeof(size));
uint32_t bit_size;
in.read(reinterpret_cast<char*>(&bit_size), sizeof(bit_size));
while(size-- > 0)
{
uint32_t key_size;
in.read(reinterpret_cast< char*>(&key_size), sizeof(key_size));
std::string key(key_size, '\0');
char value;
in.read(&key[0], key_size);
in.read(&value, sizeof(value));
code[key] = value;
}


std::string stream;
uint8_t byte;
while (in.read(reinterpret_cast<char*>(&byte), sizeof(byte)))
{
std::bitset<8> bs(byte);
if(bit_size < 8)
{
stream += bs.to_string().substr(0, bit_size);
}
else stream += bs.to_string();
bit_size -= 8;
}
in.close();

std::ofstream out("huf_"+filename, std::ios::binary|std::ios::out);
if(!out)
{
std::cerr << "open file failed" << std::endl;
return;
}
std::string match = "";
for (char &c : stream)
{
match += c;
if (code.find(match) != code.end())
{
out.put(code[match]);
match.clear();
}
}
out.close();
}

void printweight()
{
for (auto &p : weight)
{
std::cout << p.first << " " << p.second << std::endl;
}
}

void printrate()
{
struct stat st1,st2;
stat(filename.c_str(), &st1);
std::cout << "origin file size: " << st1.st_size << std::endl;
stat((filename+".huf").c_str(), &st2);
std::cout << "huf file size: " << st2.st_size << std::endl;
std::cout << "compress rate: " << (double)(st2.st_size) / st1.st_size << std::endl;
}
};

int main()
{
HuffmanTree tree("input");
tree.readFile();
tree.create_HuffmanTree();
tree.Hcode("", tree.gettree());
tree.printweight();
tree.printCode();
tree.encode();
tree.decode();
tree.printrate();
return 0;
}

只能压缩普通文件,小文件压缩因为还要存储哈夫曼编码信息只会适得其反,压缩后文件占50%~90%都有

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
\ 1
' 2
h 74
- 18
. 71
i 243
f 85
+ 15
g 44
, 36
y 27
> 52
b 32
p 90
_ 62
q 11
m 57
2 10

240
a 132
& 25
r 242
# 11
d 159
) 133
/ 2
n 156
3 6
1997
[ 8
c 125
( 133
v 15
; 113
< 91
w 26
l 86
1 6
u 94
: 142
e 387
* 10
o 168
s 230
8 9
t 367
H 19
T 5
{ 34
N 7
} 34
= 28
F 2
! 8
" 40
] 8
k 14
0 8
z 46
C 2
| 4
11
i 10111
l 010110
1 1001001001
o 01010
" 0100101
] 000001010
H 01001001
8 010010000
s 10011
* 010010001
e 1000
d 01000
) 00011
n 00111
3 1001001000
h 001101
- 00100101
. 001100
: 00101
u 011110
f 010011
+ 101010111
, 0010011
g 0101111
! 001001001
\ 010111000010
v 00000100
; 100101
0 000001011
k 100100101
( 00010
c 101011
b 0000011
' 01011100000
_ 000000
| 0010010000
a 00001
& 01111110
{ 0010000
C 00100100010
} 0010001
F 00100100011
/ 010111000011
T 0101110001
2 010111001
m 1010100
# 010111010
q 010111011
t 0110
p 011100
< 011101
w 01111111
z 0111110
> 1001000
y 10010011

10100
= 10101010
N 1010101100
[ 1010101101
r 10110
origin file size: 6302
huf file size: 4206
compress rate: 0.667407