Huffman Coding V1

本文介绍了一种基于霍夫曼树的编码实现方法。通过递归构建霍夫曼树并为每个节点分配编码,实现了高效的数据压缩。文章详细解释了编码构造过程,并通过实例演示了如何使用栈来辅助构建霍夫曼树。

//编码构造过程很受启发,有一个节点就可以确定子节点的编码,如此递归下去。还有数组的头指针不改变,按从大到小的顺序排列。栈里的指针变量并不是外面的副本,好像是别名,这个有待验证;

#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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值