#include <iostream>
#include <vector>
struct huffman_element {
huffman_element() {
weight = 0;
lchild = -1;
rchild = -1;
parent = -1;
}
double weight;
int lchild;
int rchild;
int parent;
};
class huffman_tree {
public:
explicit huffman_tree(const std::vector<double>&weight_array) {
init_tree(weight_array);
construct(weight_array.size());
}
huffman_tree(const huffman_tree &) = delete;
const huffman_tree & operator = (const huffman_tree &) = delete;
virtual ~huffman_tree() = default;
public:
void print() {
for (int i = 0;i < tree_.size();i++) {
std::cout << "(weight:" << tree_[i].weight << ",parent:" << tree_[i].parent << ",lchild:" << tree_[i].lchild << ",rchild:" << tree_[i].rchild << ")" << std::endl;
}
}
private:
void init_tree(const std::vector<double>&weight_array) {
int n = weight_array.size();
int size = n * 2 - 1;
tree_.resize(size);
for (int i = 0;i < n;i++) {
tree_[i].weight = weight_array[i];
}
}
void select_min(int size, int &index0, int &index1) {
for (int i = 0;i < size;i++) {
if (-1 == tree_[i].parent) {
index0 = i;
break;
}
}
for (int i = 0;i < size;i++) {
if (-1 == tree_[i].parent && tree_[i].weight < tree_[index0].weight) {
index0 = i;
}
}
for (int i = 0;i < size;i++) {
if (-1 == tree_[i].parent && i != index0) {
index1 = i;
break;
}
}
for (int i = 0;i < size;i++) {
if (-1 == tree_[i].parent && tree_[i].weight < tree_[index1].weight && i != index0) {
index1 = i;
}
}
}
void construct(int start) {
int size = tree_.size();
for (int k = start;k < size;k++) {
int index0 = -1;
int index1 = -1;
select_min(k, index0, index1);
tree_[index0].parent = k;
tree_[index1].parent = k;
tree_[k].lchild = index0;
tree_[k].rchild = index1;
tree_[k].weight = tree_[index0].weight + tree_[index1].weight;
}
}
private:
std::vector<huffman_element>tree_;
};
int main() {
std::vector<double>weight_array{ 5, 29, 7, 8, 14, 23, 3, 11 };
huffman_tree huffman(weight_array);
huffman.print();
return 0;
}