#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
map<string, string> code;
// Huffman 数的结点
struct Node
{
int key; // 权值
string c; // 哪个字符
Node* lchild;
Node* rchild;
Node(int key, string c) : key(key), c(c), lchild(NULL), rchild(NULL) {}
};
int frequency[maxn]; // 每种字符的频率
Node* ptr;
deque<Node*> forest; // 森林
void printCode(deque<bool> ptr);
bool compare( Node *a, Node *b) {
return a->key < b->key;
}
void get_code(Node* u, string cd)
{
if(!u->lchild && !u->rchild) {
code[u->c] = cd;
return ;
}
else {
get_code(u->lchild, cd + "0");
get_code(u->rchild, cd + "1");
}
}
int main() {
freopen("i.txt", "r", stdin);
int n;
cin >> n; // 输入字符的数量
for (int i = 0; i < n; i++) {
string c;
cin >> frequency[i] >> c; // 輸入10個權值
ptr = new Node(frequency[i], c);
ptr->key = frequency[i];
ptr->lchild = NULL;
ptr->rchild = NULL;
forest.push_back(ptr);
}
for (int i = 0; i < n - 1; i++) {
sort(forest.begin(), forest.end(), compare);
ptr = new Node(0, "");
ptr->key = forest[0]->key + forest[1]->key;
ptr->lchild = forest[0];
ptr->rchild = forest[1];
forest.pop_front();
forest.pop_front();
forest.push_back(ptr);
}
ptr = forest.front();
get_code(ptr, "");
for(auto & it : code) {
cout << it.first << ": " << it.second << endl;
}
return 0;
}
算法作业——Huffman编码
最新推荐文章于 2024-04-16 15:40:24 发布