哈夫曼树 源代码
来源:互联网 发布:淘宝拍a发b那个平台好 编辑:程序博客网 时间:2024/05/23 00:09
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
typedef struct node
{
int weight;
int parent;
int lchild;
int rchild;
}H_node,*H_tree;
void print(H_tree t,int n)
{
int i;
for(i=0;i<2*n-1;++i)
{
cout<<setw(3)<<t[i].weight<<setw(3)<<t[i].parent<<setw(3)<<t[i].lchild<<setw(3)
<<t[i].rchild<<endl;
}
}
void create(H_tree&t,int *p,int n)
{
t=new H_node[2*n-1];
int i;
for(i=0;i<2*n-1;++i)
{
t[i].parent=0;
if(i<n)
t[i].weight=p[i];
else t[i].weight=0;
t[i].lchild=0;
t[i].rchild=0;
}
}
void Find_min(H_tree t,int&min1,int&min2,int n)
{
int i;
int x1,x2;x1=x2=100000000;
for(i=0;i<n;++i)
{
if(t[i].parent==0&&x1>t[i].weight)
{
x2=x1; min2=min1;
x1=t[i].weight;
min1=i;
}
else
if(t[i].parent==0&&x2>t[i].weight)
{
x2=t[i].weight;
min2=i;
}
}
}
void Hufmantree(H_tree&t,int n)
{
int i,min1,min2;
for(i=n;i<2*n-1;++i)
{
Find_min(t,min1,min2,i);
t[i].weight=t[min1].weight+t[min2].weight;
t[min1].parent=i;t[min2].parent=i;
t[i].lchild=min1;t[i].rchild=min2;
}
}
void Print_H_tree(H_tree t,int n)
{
int i,k,j;int h;
cout<<"哈弗曼编码如下/n";
for(i=0;i<n;++i)
{
string s;
h=0;
k=i;
cout<<t[i].weight<<" ";
while(t[k].parent!=0)
{
j=t[k].parent;
if(t[j].lchild ==k)s.insert(h,"0");
else s.insert(h,"1");
k=j;
h++;
}
for(string::iterator i=s.end()-1;i>=s.begin();i--)
cout<<*i;
cout<<endl;
}
}
int main()
{
int p[]={7,9,2,6};int n=4;//n为叶子节点个数
H_tree t=NULL;
create(t,p,n);Hufmantree(t,n);print(t,n);
Print_H_tree(t,n);
return 0;
}
- 哈夫曼树 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- 源代码
- PK ACM 1021
- 键盘拖毛与键盘遮蔽
- mysql 获取当前的时间戳
- 我很失望,因为,其实如何计算phase lag, 如何矫正Heat capacity, 还是不大明白
- 内存泄漏
- 哈夫曼树 源代码
- html 表格细边框处理
- 当系统闲置时(鼠标,键盘长时间不动),用户定制的回调
- 史上最简单的pro*c程序
- html 屏蔽右键 屏蔽左键选取
- 《Visual C# 最佳实践》第一章 程序设计 (一):程序概念
- vc6.0 中关于友元的一个问题
- C#数组学习
- Cognos 8.3的安装