hdu1053(哈夫曼编码)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1053

题意是,给出一排字符串,要求求出字符的8位编码的长度,哈夫曼编码值,以及之间的比值

因为仅仅只要求求出哈夫曼编码值,所以不用建立哈夫曼树,可以建立优先队列,只要将每次最小的

出队的两个元素合成一个新的大数,然后放进优先队列中,直到只剩下一个元素为止,那个元素就是哈夫曼编码值。

注意只有一种字符的情况

ac代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
int main(){
  int a[30];
  string s;
  while(cin>>s){
  	memset(a,0,sizeof(a));
  	if(s=="END")//结束标志
    break;
  	int l=s.length();
     for(int i=0;i<l;i++){
     	if(s[i]=='_')
     	a[26]++;
     	else
     	a[s[i]-'A']++;
	 }
     priority_queue<int,vector<int>,greater<int> >q;
     for(int i=0;i<=26;i++){
     	if(a[i])
     	q.push(a[i]);
	 }
	 int sum=0;
	 while(q.size()>1){
	 	int x=q.top();q.pop();
	 	int y=q.top();q.pop();
	 	q.push(x+y);
	 	sum+=(x+y);
	 } 
	 if(sum==0){
	 	sum=l;
	 }
	 printf("%d %d %.1lf\n",l*8,sum,(l*8.0)/(sum*1.0));
  }
  return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值