《算法分析与设计》 -作业11 最优前缀码

一、问题

给定字符集C={x1,x2,…,xn}和每个字符集的频率f(x1),求关于C的一个最优前缀码。

二、解析

构造最优前缀码的贪心算法就是哈夫曼算法。根据各个字符的权值建立一颗哈夫曼树,求得每个字符的哈夫曼编码,有了每个字符的哈夫曼编码,我们就可以制作一个该字符集的哈夫曼编码表。有了字符集的哈夫曼编码表之后,对数据文件的编码过程就是依次读人文件中的字符ch,在哈夫曼编码表中找到此字符,将字符ch转换为对应的哈夫曼编码串。

三、设计
void buildHuffmanTree(int n){
    for (int i=0; i<n*2-1; ++i) {//初始化
        huffman[i].weight=0;
        huffman[i].parent=-1;
        huffman[i].leftchild=-1;
        huffman[i].rightchild=-1;
    }
    for (int i=0; i<n; i++) {
        printf("请分别输入第%d个哈夫曼字符和权重",i);
        std::cin >> huffman[i].ch;
        scanf("%d",&huffman[i].weight);
    }
    int x1,x2,w1,w2;
    for (int i=0; i<n-1; i++) {
        x1=x2=-1;
        w1=w2=MAXWEIGHT;
        for (int j=0; j<n+i; j++) {
            if (huffman[j].parent==-1&&huffman[j].weight<w1) {
                w2=w1;//如果每次最小的更新了,那么需要把上次最小的给第二小的
                x2=x1;
                x1=j;
                w1=huffman[j].weight;
            }
            else if (huffman[j].parent==-1&&huffman[j].weight<w2){
                x2=j;
                w2=huffman[j].weight;
            }
        }
        //找到最小的两个节点后要记得合并成一个新的节点
        huffman[n+i].leftchild=x1;
        huffman[n+i].rightchild=x2;
        huffman[n+i].weight=w1+w2;
        huffman[x1].parent=n+i;
        huffman[x2].parent=n+i;
    }
}
void Print(int n){
    HuffmanCode hcode;   //保存当前叶子节点的字符编码
    int curParent;       //当前父节点
    int c;               //下标和叶子节点的编号
    for (int i = 0; i < n; ++i){
        hcode.start = n - 1;
        c = i;
        curParent = huffman[i].parent;
        while (curParent != -1){//我们先拿到父节点,然后判断左节点是否为当前值,如果是取节点0,否则取节点1
            if (huffman[curParent].leftchild == c){
                hcode.code[hcode.start] = 0;
            }
            else{
                hcode.code[hcode.start] = 1;
            }
            hcode.start--;
            c = curParent;
            curParent = huffman[c].parent;
        }
        //把当前的叶子节点信息保存到编码结构体里面
        for (int j = hcode.start + 1; j < n; j++){
            code[i].code[j] = hcode.code[j];
        }
        code[i].start = hcode.start;
    }
}
四、分析

O(nlogn)频率排序;for循环O(n),插入操作O(logn)。算法复杂度是O(nlogn)。
源码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值