POJ 1521
来源:互联网 发布:淘宝秋天卖什么最火 编辑:程序博客网 时间:2024/05/15 22:37
这道题题目有点长,看了之后 发现时 哈夫曼编码问题,对给定对字符串中的每一个字母编码,使得整个编码序列最短。
因为这道题最后只要求编码的长度,所以用优先队列就 可以解决。
这里注意一下,优先队列的声明格式:
/priority_queue 对于基本类型的使用方法相对简单。他的模板声明带有三个参数:
//priority_queue<Type, Container, Functional>
//其中Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
//Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
//STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,
//优先队列就是大顶堆,队头元素最大。
priority_queue<int,vector<int>,greater<int> >Q;
这样从Q中取出的元素就是最小的。
分析:将Q前两个元素取出,然后求和,将两元素只和再次入队,这样无形中就构造了 一个哈夫曼树,所有节点的值的和 就是编码的长度。
当然,这里也可以直接构造哈夫曼树来求解,会比较繁琐,待我先 复习一下 哈夫曼 编码的知识再说。
最后注意输出比率时保留一位小数,cout<<fixed<<setprecision(1)<<x<<endl; 别忘了加上头文件iomanip
#include<iostream>#include<queue>#include<string>#include<map>#include<iomanip>using namespace std;map<char,int>mp;map<char,int>::iterator iter;priority_queue<int,vector<int>,greater<int>> Q;int main(){ string str; while(cin>>str,str!="END"){ mp.clear(); for(int i=0;i<str.length();i++){ mp[str[i]]++; } for(iter=mp.begin();iter!=mp.end();iter++){ Q.push(iter->second); } int sum = 0; while(Q.size()>1){ int a = Q.top(); Q.pop(); int b = Q.top(); Q.pop(); sum = sum + a + b; Q.push(a+b); //把新节点重新入队 } if(sum == 0) sum = str.length(); while(!Q.empty()) Q.pop(); cout<<8*str.length()<<" "<<sum<<" "<<fixed<<setprecision(1)<<double(8*str.length())/sum<<endl; } return 0;}
0 0
- poj 1521
- poj-1521
- POJ 1521
- POJ 1521 Entropy
- poj 1521 Entropy
- POJ 1521 哈夫曼树
- poj 1521 Entropy
- POJ 1521 Entropy
- POJ 1521 Entropy
- POJ 1521 && HDOJ 1053
- POJ - 1521 Entropy
- Huffman编码 POJ 1521
- POJ 1521 Jungle Roads
- poj 1521 Entropy
- POJ 1521 , Entropy , Huffman
- POJ
- poj
- POJ
- Android学习笔记----Activity的三个小的技巧
- win7下面VM VirtualBox中linux CenOS 网络的配置
- iOS开发之静态库-基本概念
- A activity 跳转 B activity ,B 销毁时A也一起销毁
- android中常见的设计模式有哪些?
- POJ 1521
- Maven--构建企业级仓库(二)
- JAVA IO最常用类及实例
- 绿色单选按钮以及复选框
- with temp as 定义变量
- 安卓多线程编程系列7:使用Looper的不同方式(子线程中实例化Handler方式)
- 小数 二进制 的 表示与转换
- 红包倒计时
- c# 照片轮播控件