Huffman coding

本文介绍了一种使用哈夫曼编码进行数据压缩的方法,并通过一个具体的编码实例详细展示了如何构建哈夫曼树并计算编码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 asB(T), to encode the data:

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

wheref(c) is the frequency of character c, and dT(c) is be the depth of characterc's leaf in the tree T.

 
Input

The first line is the number of characters n.

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

Output

 Output a single number B(T).

Sample Input
Copy sample input to clipboard
5
0 5
1 4
2 6
3 2
4 3
Sample Output
45
Hint
0: 01
1: 00
2: 11
3: 100
4: 101


这道题是哈夫曼编码,主要是优先队列没用好,数据类型的指针变量应该这么传参才能小根堆,如果是普通变量可以直接在结构体里重载 < 即可,其余没什么


#include <iostream>
#include <queue>
#include <map>

using namespace std;

struct huffman{
    char c;
    int num;
};

struct tree{
    huffman h;
    tree* left;
    tree* right;
    
}; 
struct cmp{
	bool operator() (tree const*a, tree const*b){
		return a->h.num > b->h.num;
	}
};//小根堆比较 
map <char,int> mm;

void deal(tree* t,int n){
    if(t->left==NULL&&t->right==NULL){
        mm[t->h.c]=n;
    }
    else {
        deal(t->left,n+1);
        deal(t->right,n+1);
    }
}//计算树的深度,用于计算字符长度 
int main()
{
    int n;
    cin >> n;
    priority_queue <tree*, vector<tree*>, cmp> pq;
    huffman hu[1001];
    for(int i=0; i < n; ++i){
        cin >> hu[i].c >> hu[i].num;
        tree *tmp=new tree;
        tmp->h=hu[i];
        tmp->left=NULL;
        tmp->right=NULL;
        pq.push(tmp);
    }//将字符存进优先队列 
    /*tree* t=pq.top();
	cout << t->h.c << endl; */
    while(pq.size() > 1){
        tree* t1=pq.top();
        //cout << t1->h.c << "   "<<t1->h.num << endl;
        pq.pop();
        tree* t2=pq.top();
        //cout << t2->h.c << "   "<< t2->h.num << endl;
        pq.pop();
        tree *tmp=new tree;
        tmp->h.c='.';
        tmp->h.num=t1->h.num+t2->h.num;
        tmp->left=t1;
        tmp->right=t2;
        pq.push(tmp);
        //cout << endl;
    }//建立哈夫曼编码树 
    tree* res=pq.top();
    //cout << res->h.num << endl;
    deal(res,0);
    int resu=0;
	for(int i=0; i < n; ++i){
		//cout << hu[i].num << "   "  << mm[hu[i].c] << endl;
		resu+=(hu[i].num*(mm[hu[i].c]));	
	}
	cout << resu << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值