#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;
}