北大ACM3253 - Fence Repair(赫夫曼编码)

本文介绍了一种使用优先级队列实现赫夫曼编码的方法,并通过一个具体实例展示了如何构建赫夫曼树来最小化编码总长度。文章详细解释了赫夫曼编码原理及其在压缩算法中的应用。

1.1      算法分析

赫夫曼编码

由于这个问题,考察的是赫夫曼编码,所以优先级队列就直接使用STL的了。

1.2      代码

 

/*
 *
 * Introduction : ACM of pku
 * ID : 3253
 * alg : Huffman
 * Author : Gykimo
 * Date : 20121203
 * 
 */

#include <stdlib.h>
#include <stdio.h>
#include <queue>

using namespace std;

struct cmp
{
	bool operator ()(int x, int y){
		return x > y;
	}
};

int planks_num = 0;
int *planks = NULL;
long long min_amount = 0;

void readLine(){
	scanf("%d", &planks_num);
	planks = (int *)malloc(planks_num * sizeof(int));
	
	for(int i=0; i<planks_num; i++){
		scanf("%d", planks+i);
	}
}

void display(){
	printf("%lld\n", min_amount);
}

void huffman(){
	priority_queue<int, vector<int>, cmp> q(planks, planks+planks_num);

	int first, second, sum;
	while(q.size() > 1){
		first = q.top();
		q.pop();
		second = q.top();
		q.pop();
		sum = first + second;
		q.push(sum);
		min_amount += sum;
	}
}

int main(){
	readLine();
	huffman();
	display();
	return 0;
}


1.3      运行结果

 724K 47MS

1.4      总结

主要注意, 结果不能是int,容易过界。

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值