-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathHuffman.h
64 lines (40 loc) · 1.69 KB
/
Huffman.h
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
#ifndef HUFFMAN_H
#define HUFFMAN_H
#include <memory>
#include <string>
#include <vector>
class Huffman {
private:
inline static int R = 256; // ASCII alphabet
struct Node {
char ch;
int freq;
const std::shared_ptr<Node> left, right;
Node(char ch, int freq, const std::shared_ptr<Node> &left,
const std::shared_ptr<Node> &right) : ch(ch), freq(freq), left(left), right(right) {}
bool isLeaf() const { return !left && !right; }
friend bool operator<(const Node &l, const Node &r) { return l.freq < r.freq; }
friend bool operator>(const Node &l, const Node &r) { return r < l; }
};
static std::vector<std::string> buildCode(const std::shared_ptr<Node> &root);
static void buildCode(std::vector<std::string> &st, const std::shared_ptr<Node> &x, const std::string &s);
static std::shared_ptr<Node> buildTrie(const std::vector<int> &freq);
static void writeTrie(const std::shared_ptr<Node> &x);
static std::shared_ptr<Node> readTrie();
public:
// comparable std::shared_ptr<Node> wrapper
class NodePtr {
private:
std::shared_ptr<Node> nodePtr;
public:
NodePtr(const std::shared_ptr<Node> &sp) : nodePtr(sp) {}
operator std::shared_ptr<Node>() const { return nodePtr; }
Node *operator->() { return nodePtr.operator->(); }
const Node *operator->() const { return nodePtr.operator->(); }
friend bool operator<(const NodePtr &l, const NodePtr &r) { return *l.nodePtr < *r.nodePtr; }
friend bool operator>(const NodePtr &l, const NodePtr &r) { return r < l; }
};
static void compress();
static void expand();
};
#endif //HUFFMAN_H