#include<iostream>
#include<vector>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<sstream>
using namespace std;
/*
此程序是用来模拟哈夫曼编码
*/
/*
ch 用来储存ASICC
count用存储字符的数目
isal用来记录编码树中的结点是否为字母结点
left,right 指向左右结点
*/
struct node {
char ch;
int count;
bool isal;
struct node* left;
struct node* right;
};
/*
此为map<struct node*,vector<struct node*> cmp> Q中的比较关键字
*/
struct cmp {
bool operator () (struct node* n1, struct node* n2)
{
return n2->count < n1->count;
}
};
/*
用优先队列来生成哈夫曼树
*/
struct node* Bulid(priority_queue<struct node*, vector<struct node*>, cmp> Q)
{
if (Q.size() == 0) {
return NULL;
}
else if (Q.size() == 1) {
return Q.top();
}
do {
struct node* n = new struct node;
n->isal = false;
n->left = Q.top();
Q.pop();
n->right = Q.top();
Q.pop();
n->count = n->left->count + n->right->count;
Q.push(n);
} while (Q.size() > 1);
return Q.top();
}
/*
用已经统计好的字符和其数量对应的映射关系,递归生成哈夫曼编码
*/
void Code(struct node* root,string s, map<char, string>& Map)
{
if (root) {
if (root->isal == true) {
Map[root->ch] = s;
}
Code(root->left, s + "0", Map);
Code(root->right, s + "1", Map);
}
}
/*
将文件C:\\Users\\DELL\\Desktop\\in.txt中的内容读入,进行编码并输出到C:\\Users\\DELL\\Desktop\\out.txt
*/
void Encrypte(map<char, string> Map)
{
ifstream inFile("C:\\Users\\DELL\\Desktop\\in.txt", ios::in);
ofstream out("C:\\Users\\DELL\\Desktop\\out.txt", ios::out);
char ch;
string s;
while (getline(inFile, s)) {
for (size_t i = 0; i < s.size(); ++i) {
ch = s[i];
out << Map[ch];
}
}
out.close();
inFile.close();
}
/*
对文件C:\\Users\\DELL\\Desktop\\out.txt中的内容进行解码,并输出到控制台
*/
void Decrypt(map<char, string> Map)
{
map<string, char> M;
for (map<char, string>::iterator it = Map.begin(); it != Map.end(); ++it) {
M[it->second] = it->first;
}
string s = "";
ifstream inFile("C:\\Users\\DELL\\Desktop\\out.txt", ios::in);
ofstream out("C:\\Users\\DELL\\Desktop\\in1.doc", ios::out);
char ch;
while (inFile >> ch) {
s += ch;
map<string, char>::iterator it = M.find(s);
if (it != M.end()) {
out << it->second;
cout << it->second;
s = "";
}
}
cout << endl;
inFile.close();
out.close();
}
int main()
{
ifstream inFile("C:\\Users\\DELL\\Desktop\\in.txt", ios::in);
char ch;
string s;
map<char, int> Map;
//将文件中的字符进行统计,并生成映射表
while (getline(inFile, s)) {
for (size_t i = 0; i < s.size(); ++i) {
ch = s[i];
if (Map.find(ch) == Map.end()) {
Map[ch] = 1;
}
else {
Map[ch]++;
}
}
}
inFile.close();
//将映射表中的内容,转变为哈夫曼树结点,为生成哈夫曼树进行初步
priority_queue<struct node*, vector<struct node*>, cmp> Q;
for (map<char, int>::iterator it = Map.begin(); it != Map.end(); ++it) {
struct node* n=new struct node;
n->isal = true;
n->ch = it->first;
n->count = it->second;
n->left = n->right = NULL;
Q.push(n);
}
struct node* root = Bulid(Q);
map<char, string> Map1;
Code(root, "", Map1);
Encrypte(Map1);
Decrypt(Map1);
/*
for (map<char, string>::iterator it = Map1.begin(); it != Map1.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
*/
system("pause");
return 0;
}