POJ1521哈夫曼编码

本文介绍了如何不构建哈夫曼树,而是通过使用优先队列来实现哈夫曼编码的过程。这种方法通过每次合并权值最小的两个元素来达到哈夫曼树的构建效果。
摘要由CSDN通过智能技术生成

 思路:

参照哈夫曼编码,可以不用建树,用优先队列,每次把权值最小的两个加起来再入队,做到哈夫曼树的效果。

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1005;
char str[maxn];
struct node{
	int x;
	bool operator <(const node a)const{
		return x>a.x;
	}
}count[maxn];
int main(){
	priority_queue<node>pq;
	int sum=0;
	while(scanf("%s",str)&&strcmp(str,"END")){
		sum=0;
		memset(count,0,sizeof(count));
	
		for(int i=0;i<strlen(str);i++){
			count[str[i]].x++;
		}
		for(int i=0;i<200;i++){
			if(count[i].x){
				pq.push(count[i]);
				count[i].x=0;
			} 
		}
		while(pq.size()>1){
			node temp1=pq.top();
			pq.pop();
			node temp2=pq.top();
			pq.pop();
			sum+=temp1.x+temp2.x;
			pq.push(node{temp1.x+temp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值