用哈弗曼树编码字符串 求出编码后字符串二进制位长度

大家对哈弗曼编码应该很熟悉,哈弗曼编码最大的一个用处就是压缩存储,本文要讲的不是如何编码,而是求出对字符串编码后的二进制位的长度。
估计一般的同学都会有思路,最简单的思路就是先构建好哈弗曼树,然后编码,然后求长度,这个思路很简单但是下面给出一个用c++写的一个程序,
效率比较高:
    #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <utility>
#include <queue>

#include <iostream>
using namespace std;
/*本程序 统计 用哈弗曼编码 编一个字符串 最后编码的二进制位数*/
int main()
{
    char s[3300];
    while(scanf("%s",s) != EOF)
    {
        int n = strlen(s);
        sort(s,s + n);
        priority_queue<int> heap;
        int cnt = 0;
        for(int i = 0,j; i < n;)
        {
            j = i;
            while(j < n && s[j] == s[i]) ++ j;
            heap.push(i - j);
            i = j;
            ++ cnt;
        }
        int ret = 0;
        for(int i = 0; i < cnt - 1; ++ i)
        {
            int A = heap.top();
            heap.pop();
            int B = heap.top();
            heap.pop();
            ret -= A + B;
            heap.push(A + B);
        }
        printf("%d\n",ret);
    }
    return 0;
}
还望与大家一起感受编程的精妙。
    原文作者:哈夫曼树
    原文地址: https://blog.csdn.net/wlp001007/article/details/49336833
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞