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

来源:互联网 发布:战舰世界大和数据穿深 编辑:程序博客网 时间:2024/06/07 10:33
大家对哈弗曼编码应该很熟悉,哈弗曼编码最大的一个用处就是压缩存储,本文要讲的不是如何编码,而是求出对字符串编码后的二进制位的长度。估计一般的同学都会有思路,最简单的思路就是先构建好哈弗曼树,然后编码,然后求长度,这个思路很简单但是下面给出一个用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;}
还望与大家一起感受编程的精妙。
0 0
原创粉丝点击