# 霍夫曼编码

270人阅读 评论(0)

Description

Input

Output

Sample Input
Copy sample input to clipboard
10
S S U U U S U L U U

Sample Output
U 6 1
S 3 01
L 1 00


struct Node {
int value;    // 记录频率
char c;       // 记录字符
std::string code;   // 记录编码
Node* l;            // 左孩子
Node* r;            // 右孩子
Node(int num, int index) { };   //num为频率, index用来确定是那个字符
} *nodes[26];

if (root->l != NULL) {
root->l->code = root->code + "0";
dfs(root->l);
}同理确定右孩子的编码

#include <iostream>
#include <stack>
#include <algorithm>
#include <memory.h>

struct Node {
int value;
char c;
std::string code;
Node* l;
Node* r;
Node(int num, int index) {
value = num;
c = 'A' + index;
code = "";
l = r = NULL;
}
} *nodes[26];

bool com(Node* a, Node* b) {
return a->value > b->value;
}

void dfs(Node* root) {
if (root->l != NULL) {
root->l->code = root->code + "0";
dfs(root->l);
}
if (root->r != NULL) {
root->r->code = root->code + "1";
dfs(root->r);
}
}

int main()
{
int num;
std::cin >> num;
int arr[26];
memset(arr, 0, sizeof(arr));
char temp;
int count = 0;
for (int i = 0; i < num; ++i) {
std::cin >> temp;
if (arr[temp-'A'] == 0)
count++;
arr[temp-'A']++;
}
//std::cout << count << std::endl;
int index = 0;
for (int i = 0; i < 26; ++i) {
if (arr[i] > 0) {
nodes[index++] = new Node(arr[i], i);
}
}

std::stack<Node*> s;
while (count != 1) {
std::sort(nodes, nodes+count, com);
if (nodes[count-1]->l == NULL && nodes[count-1]->r == NULL)
s.push(nodes[count-1]);
if (nodes[count-2]->l == NULL && nodes[count-2]->r == NULL)
s.push(nodes[count-2]);
Node* father = new Node(nodes[count-1]->value + nodes[count-2]->value, 0);
father->l = nodes[count-1];
father->r = nodes[count-2];
nodes[count-2] = father;
count--;
}
//std::cout << count << std::endl;
dfs(nodes[0]);
//std::cout << "coding end" << std::endl;
while (!s.empty()) {
std::cout << s.top()->c << " " << s.top()->value << " " << s.top()->code << std::endl;
s.pop();
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：26258次
• 积分：1273
• 等级：
• 排名：千里之外
• 原创：104篇
• 转载：0篇
• 译文：1篇
• 评论：3条
文章分类
阅读排行
评论排行
最新评论