poj1521
来源:互联网 发布:雅虎股票数据接口 编辑:程序博客网 时间:2024/05/21 16:26
Problem: Entropy
Description: 有一些单词我们需要用二进制存储起来,但是单词出现的频率不一样,我们可以把那些出现频率高的字母的编码短一些,这样可以节省空间。用定长的编码来存储的话需要用8位二进制码来存储26个字母还有一个’_’符号。
Solution: 典型的哈弗曼编码,先哈弗曼过一遍,得到那些字符的编码,然后算出所需的空间。再用8*字符长度得到定长编码所需的空间,然后得到两种方式的比值。
Code(C++):
#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <queue>#include <iomanip>using namespace std;typedef struct tagQue{ int value; int id; tagQue() {} tagQue(int value,int id) { this->value=value; this->id=id; } bool operator<(const tagQue &other)const { return !(this->value<other.value); }} Que;struct HtNode{ char c; int cn; int parent,lchild,rchild; HtNode() {} HtNode(char c,int cn,int parent,int lchild,int rchild) { this->c=c; this->cn=cn; this->parent=parent; this->lchild=lchild; this->rchild=rchild; }};int cnt[30];string Hc[100];HtNode Ht[100];priority_queue<Que> q;void Select(int &x,int &y){ x=q.top().id; q.pop(); y=q.top().id; q.pop();}void HuffmanCoding(HtNode HT[],string HC[],int n){ int i,t,f; int m=2*n-1; for(i=0; i<n; i++) HT[i]=Ht[i]; for(i=n; i<m; i++) HT[i]=HtNode(' ',0,0,0,0); for(i=n; i<m; i++) { int s1,s2; Select(s1,s2); HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].cn=HT[s1].cn+HT[s2].cn; q.push(Que(HT[i].cn,i)); } string str; for(i=0; i<n; i++) { str.erase(); for(t=i,f=HT[i].parent; f!=0; t=f,f=HT[f].parent) { if(HT[f].lchild==t) str.append("0"); else str.append("1"); } reverse(str.begin(),str.end()); HC[i]=str; }}int main(){ string str; int length,i,t; int sum; while(cin>>str,str!="END") { t=0;sum=0; memset(cnt,0,sizeof(cnt)); length=str.size(); for(i=0; i<length; i++) { if(str.at(i)>='A'&&str.at(i)<='Z') cnt[str.at(i)-'A']++; else cnt[str.at(i)-'_'+26]++; } for(i=0; i<=26; i++) { if(cnt[i]==0) continue; if(i==26) { Ht[t].c='_'; Ht[t].cn=cnt[i]; Ht[t].parent=0; Ht[t].lchild=0; Ht[t++].rchild=0; } else { Ht[t].c=char(i+'A'); Ht[t].cn=cnt[i]; Ht[t].parent=0; Ht[t].lchild=0; Ht[t++].rchild=0; } } for(i=0;i<t;i++) q.push(Que(Ht[i].cn,i)); HuffmanCoding(Ht,Hc,t); for(i=0;i<t;i++) { int len=Hc[i].size(); sum+=Ht[i].cn*len; } cout<<length*8<<" "<<sum<<" "; cout<<setiosflags(ios::fixed)<<setprecision(1)<<float(length*8)/sum<<endl; } return 0;}
0 0
- poj1521
- poj1521
- POJ1521
- poj1521
- poj1521(huffman)
- poj1521 huffman
- poj1521 Entropy
- poj1521 (huffman +优先队列)
- [POJ1521]Huffman编码
- #POJ1521#Huffman编码
- [POJ1521]Huffman编码
- poj1521 求赫夫曼编码长度
- ZOJ1117 POJ1521 HDU1053 Huffman编码
- ZOJ1117 POJ1521 HDU1053 Entropy,哈夫曼编码问题
- poj1521 指数型母函数 整数分式
- HDU1053,POJ1521,ZOJ1117 Entropy 哈夫曼编码
- 【POJ1521】【HDU1053】Entropy 哈夫曼(Huffman)编码
- POJ1521---哈夫曼编码,求最优WPL
- Android S端配置证书
- Java反射机制 Object 与 Class 的关系 以及static方法与非静态方法的关系
- |Tyvj|NOIP2006|动态规划|P1057 金明的预算方案
- 【华为 OJ 】数字颠倒
- 深度学习算法实践2---线性代数和Numpy的使用
- poj1521
- Android5.0特性
- #123 Word Search
- SpringMVC @RequestBody接收Json对象字符串
- html TextRange的使用
- Flume学习笔记(二)问题整理
- uclibc,eglibc,glibc之间的区别和联系
- 安卓监听和修改软键盘右下角按钮
- linux下NFS文件共享的介绍和使用