<Sicily>Huffman coding

一、题目描述

In computer science and information theory, a Huffman code is an optimal prefix code algorithm.

In this exercise, please use Huffman coding to encode a given data.

You should output the number of bits, denoted as B(T), to encode the data:

B(T)=∑f(c)dT(c),

where f(c) is the frequency of character c, and dT(c) is be the depth of character c’s leaf in the tree T.

二、输入

The first line is the number of characters n.

The following n lines, each line gives the character c and its frequency f(c).

三、输出

Output a single number B(T).

例如:
输入:
5
0 5
1 4
2 6
3 2
4 3

输出:
45

四、解题思路

1、所有的节点存放在一个数组中

2、对数组按每个节点的权值从小到大进行排序
本文使用快速排序

3、取出权值最小的两个节点,生成新的节点,原来的两个节点分别为新的节点的左右子树,新节点的权值为原来两个节点的权值之和

4、把新的节点按照权值插入到已经有序的数组中

5、重复步骤3、4,直到只剩根节点

五、代码

#include<iostream>
#include<string>
#include <vector>

using namespace std;

//节点结构
struct Node{
    char ch;
    int weight;
    Node *leftChild, *rightChild;
};


//插入排序
void insertSort(Node** nodeArray, int low, int high)
{
    for(int i = low + 1; i < high; i++)
    {
        Node* temp = nodeArray[i];
        int j = i - 1;
        while(j >= low && nodeArray[j]->weight > temp->weight)
        {
            nodeArray[j+1] = nodeArray[j];
            j--;
        }
        nodeArray[j+1] = temp;
    }
}

//建Hffman树
void createHuffman(Node** nodeArray, int n)
{

    insertSort(nodeArray, 0, n);    //先对节点按weight排序
    int p = 0;
    int res = 0;
    while(p < n - 1)
    {
        Node* minNode1 = nodeArray[p];  //找出weight值最小的两个
        Node* minNode2 = nodeArray[++p];
        Node* newNode = new Node;
        newNode->weight = minNode1->weight + minNode2->weight;  //合并生成新的节点
        res += newNode->weight;

        newNode->leftChild = minNode1;
        newNode->rightChild = minNode2;
        nodeArray[p] = newNode;
        insertSort(nodeArray, p, n);
    }

    cout << res <<endl;
}


int main()
{
    int n;
    cin >> n;
    char ch;
    int weight;
    Node* nodeArray[n];
    for(int i = 0; i < n; i++)
    {
        Node* node = new Node;
        cin >> ch >> weight;
        node->ch = ch;
        node->weight = weight;
        nodeArray[i] = node;
    }
    createHuffman(nodeArray, n);
    return 0;
}
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值