数据结构---哈夫曼编码
来源:互联网 发布:js移除元素 编辑:程序博客网 时间:2024/05/29 13:20
#include<iostream>#include<string>using namespace std;#define max 100#define INF 33333333333typedef struct{string data; //结点值double weight;//权重int parent,lchild,rchild;}HTnode;HTnode ht[max];typedef struct{char cd[max];//存放当前结点的哈夫曼编码int start;//存放该结点哈夫曼编码的起始位置}HCode;HCode hcd[max];/**n:n个叶子结点,共有2n-1个结点*/void createHTnode(HTnode ht[],int n)//构造哈夫曼树{int i,k,lnode,rnode;double min1,min2;for(i=0;i<2*n-1;i++)ht[i].parent=ht[i].lchild=ht[i].rchild=-1;for(i=n;i<=2*n-2;i++){min1=min2=INF;lnode=rnode=-1;for(k=0;k<=i-1;k++)//在ht[0...i-1]中找权值最小的两个结点{if(ht[k].parent==-1){if(ht[k].weight<min1){min2=min1;rnode=lnode;min1=ht[k].weight;lnode=k;}else if(ht[k].weight<min2){min2=ht[k].weight;rnode=k;}}}ht[i].weight=ht[lnode].weight+ht[rnode].weight;ht[i].lchild=lnode;ht[i].rchild=rnode;ht[lnode].parent=i;ht[rnode].parent=i;}}void createHCode(HTnode ht[],HCode hcd[],int n0)//根据哈夫曼树求对应的哈夫曼编码{int i,f,c;HCode hc;for(i=0;i<n0;i++){hc.start=n0;c=i;f=ht[i].parent;while(f!=-1){if(ht[f].lchild==c)hc.cd[hc.start--]='0';elsehc.cd[hc.start--]='1';c=f;f=ht[f].parent;}hc.start++;//start指向哈夫曼编码的最开始的字符hcd[i]=hc;}}void display(HTnode ht[],HCode hcd[],int n){int i,k;int sum=0,m=0,cnt;cout<<"哈夫曼编码为:"<<endl;for(i=0;i<n;i++){cnt=0;cout<<ht[i].data<<"\t"<<":"; for (k=hcd[i].start; k<=n; k++) { cout<<hcd[i].cd[k]; cnt++; } m+=ht[i].weight; sum+=(ht[i].weight*cnt); cout<<endl; } cout<<"平均长度="<<(float)sum/m<<endl;}int main(){int n=15; string str[]= {"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"}; int f[]= {1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123}; for (int i=0; i<n; i++) { ht[i].data=str[i]; ht[i].weight=f[i]; } createHTnode(ht,n); createHCode(ht,hcd,n); display(ht,hcd,n); return 0; return 0;}
阅读全文
0 0
- 哈夫曼编码(数据结构)源程序
- [数据结构]哈夫曼树、哈夫曼编码
- [数据结构]哈夫曼树、哈夫曼编码
- 还是数据结构,哈夫曼编码
- 还是数据结构,哈夫曼编码
- 还是数据结构,哈夫曼编码
- 【数据结构】哈夫曼编码
- 数据结构 课程设计哈夫曼编码
- 【数据结构】哈夫曼编码
- 数据结构--哈夫曼编码
- 【数据结构基础】哈夫曼编码
- 数据结构---哈夫曼编码
- 数据结构------哈夫曼数及哈夫曼编码
- 数据结构课程设计-哈夫曼编码译码
- 数据结构—哈夫曼编码应用
- 数据结构----二叉树----哈夫曼编码
- 数据结构之哈夫曼编码,哈夫曼树
- 【数据结构】哈夫曼树及哈夫曼编码
- Aspose.Words 操作 Word文件
- 企服三会·PPT | XTools郭睿: 中国CRM过去十年和未来十年
- Python 模块
- 【Scikit-Learn 中文文档】分解成分中的信号(矩阵分解问题)
- 异常:node to traverse cannot be null! 的错误分析
- 数据结构---哈夫曼编码
- 我现在是菜鸟——Item
- Centos安装编译环境
- 数据库事务
- angular js实现公共体
- 实验吧-简单的注sql入 writeup
- ANGUALR JS学习环境搭建
- Protobuf3 + Netty4: 在socket上传输多种类型的protobuf数据
- fileZilla连接oracle服务器,传DMP文件