//编码构造过程很受启发,有一个节点就可以确定子节点的编码,如此递归下去。还有数组的头指针不改变,按从大到小的顺序排列。栈里的指针变量并不是外面的副本,好像是别名,这个有待验证;
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
struct Node {
char ch;
int val;
string code;
Node* l;
Node* r;
Node (int wei,int index):ch('A'+index),val(wei),l(NULL),r(NULL),code(""){}
}*N[35];
bool cmp(Node* N1, Node* N2) {
return N1->val>N2->val;
}
void dfs(Node* root) {
if (root->l) {
root->l->code +=root->code+"0";
dfs(root->l);
}
if(root->r) {
root->r->code += root->code+"1";
dfs(root->r);
}
}
void ini() {
int t;
cin>>t;
int arr[28];
memset(arr,0,sizeof(arr));
int count=0;
for (int i=0;i<t;i++) {
char ch;
cin>>ch;
arr[ch-'A']++;
}
for(int i=0;i<26;i++){
if (arr[i]) {
N[count++]=new Node(arr[i],i);
}
}
stack<Node*> s;
while (count!=1) {
sort(N,N+count,cmp);
if (!N[count-1]->l) s.push(N[count-1]);
if (!N[count-2]->l) s.push(N[count-2]);
Node* father = new Node(N[count-1]->val+N[count-2]->val,0);
father->l=N[count-1]; father->r=N[count-2];
N[count-2]=father;
count--;
}
dfs(N[0]);
while(!s.empty() ){
Node* k = s.top();
s.pop();
cout<<k->ch<<" "<<k->val<<" "<<k->code<<endl;
}
}
int main() {
ini();
}
本文介绍了一种基于霍夫曼树的编码实现方法。通过递归构建霍夫曼树并为每个节点分配编码,实现了高效的数据压缩。文章详细解释了编码构造过程,并通过实例演示了如何使用栈来辅助构建霍夫曼树。
2313

被折叠的 条评论
为什么被折叠?



