题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1053
其实就是以前做的最简单的哈夫曼的算法,就是这道题目的长度恶心了点
,剩下 的很简单...
题目大意:对大写和下划线进行编码,使其编码的长度最小,输出按照ASCII(八个字节)、设计的最短编码长度以及两个长度的比值(保留一位小数点)
代码:
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
int main(){
string str;
priority_queue < int,vector<int>,greater<int> > q ;
while(cin>>str&&str!="END"){
int a[35]={0};
int len=str.length() ;
for(int i=0;i<len;i++)
a[(int)(str[i]-'A')]++;
int count=0;
for(int i=0;i<=30;i++)
if(a[i]!=0){
q.push(a[i]);
count++;
}
if(count==1) { printf("%d %d %.1lf
",8*len,1*len,8.0); continue; }
int sum=0;
while(count>1){
int temp=q.top();
q.pop();
temp+=q.top();
sum+=temp;
q.pop();
q.push(temp);
count--;
}
q.pop();//将剩余的那个清空 千万注意这个清空,开始错在这个地方了,一定注意
printf("%d %d %.1lf
",len*8,sum,len*8*1.0/sum);//cout<<len*8<<' '<<sum<<' '<<len*8*1.0/sum<<endl;
}
return 0;
}