#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<queue>
#include<chrono>
using namespace std;
using namespace chrono;
struct binaChar {
char value;
int width;
};
//定义储存哈夫曼树节点
struct node {
char value;
int width;
struct node* rchild;
struct node* lchild;
};
//统计字符,赋予权值
vector<binaChar> getCharArray(int size) {
vector<binaChar> vec;
for (int i = 20; i < size + 20; i++) {
binaChar bc = { i,rand() % (i + 100) };
vec.push_back(bc);
}
return vec;
}
struct AMoreThanB{
bool operator()(node* A, node* B) {
if (A->width > B->width) return true;
else return false;
}
};
//生成哈夫曼树
void getHuffmanTree(vector<binaChar> bc, struct node*& head) {
priority_queue<node*, vector<node*>, AMoreThanB > tree;
for (int i = 0; i < bc.size(); i++) {
node* n = new node();
n->value = bc[i].value;
n->width = bc[i].width;
n->lchild = n->rchild = NULL;
tree.push(n);
}
while (tree.size() > 1) {
node* p = new node();
node* min1 = tree.top();
tree.pop();
node* min2 = tree.top();
tree.pop();
p->width = min1->width + min2->width;
p->lchild = min1;
p->rchild = min2;
tree.push(p);
}
head = tree.top();//返回构造完成的树
}
void Tran(node* root, string str, string& code, char ch) {
if (root == NULL) return;
Tran(root->lchild, str + '0', code, ch);
Tran(root->rchild, str + '1', code, ch);
if (root->value == ch) {
code = str;
return;
}
}
//加密
void getCodeFile(struct node* root, vector<binaChar> bc) {
ofstream outfile;
outfile.open("D:\\data\\infile\\coding.txt", ios::out | ios::ate);
if (!outfile) {
cout << "文件读取失败!" << endl;
return;
}
for (int i = 0; i < bc.size(); i++) {
node* p = root;
string str, temp;
Tran(p, temp, str, bc[i].value);
outfile << bc[i].value << ":" << str << endl;
}
cout << "编码写入成功!" << endl;
outfile.close();
}
int main()
{
//验证
vector<binaChar> test = { {'a',45} ,{'b',13} ,{'c',12} ,{'d',16} ,{'e',9},{'f',5} };
node* thead = new node();
getHuffmanTree(test, thead);
getCodeFile(thead, test);
cout << endl;
srand(unsigned int(time(0)));
for(int i = 30; i < 256; i ++) {
node* head = new node();
vector<binaChar> vec = getCharArray(i);
auto t0 = system_clock::now();
getHuffmanTree(vec, head);
auto t1 = system_clock::now();
auto d = duration_cast<nanoseconds>(t1 - t0);
cout << "规模:" << i << endl << "耗时:" << (double)d.count() / 1000000000 << "s" << endl;
}
}