标题:[求助]哈夫曼数的问题
取消只看楼主
鸡蛋黄
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2007-10-5
 问题点数:0 回复次数:0 
[求助]哈夫曼数的问题

近在学哈夫曼树,遇到一个程序,在C++上想试试运行一下,没有语法错误,但是结果就是运行不出来。拜托各位高手帮帮忙。
#include <iostream.h>
#include <iomanip.h>
const int n=8;
const int m=2*n-1;
struct tree
{
float weight;
int parent;
int lch,rch;
};
struct codetype
{
int bits[n+1];
int start;
char ch;
};
tree hftree[m+1];
codetype code[n+1];
void creathuffmantree()
{
int i,j,p1,p2;
float s1,s2;
for(i=1;i<=m;i++)
{
hftree[i].parent=0;
hftree[i].lch=0;
hftree[i].rch=0;
hftree[i].weight=0;
}
cout<<"请输入"<<n<<"个权值"<<endl;
for(i=1;i<=n;i++)
cin>>hftree[i].weight;
for(i=n+1;i<=m;i++)
{
p1=p2=0;
s1=s2=32767;
for(j=1;j<=i;j++)
if(hftree[j].parent==0)
if(hftree[j].weight<s1)
{s2=s1;s1=hftree[j].weight;
p2=p1;p1=j;}
else
if(hftree[j].weight<s2)
{s2=hftree[j].weight;p2=j;
}
hftree[p1].parent=i;
hftree[p2].parent=i;
hftree[i].lch=p1;
hftree[i].rch=p2;
hftree[i].weight=hftree[p1].weight+hftree[p2].weight;
}
}
void huffcode()
{
codetype cd;
int c,p;
for(int i=1;i<=n;i++)
{
cd.start=n+1;
cd.ch=96+i;
c=i;
p=hftree[i].parent;
while(p!=0)
{
cd.start--;
if(hftree[p].lch==c)
cd.bits[cd.start]=1;
else
cd.bits[cd.start]=0;
c=p;
p=hftree[p].parent;
}
code[i]=cd;
}
for(i=1;i<=n;i++)
{
cout<<"字符"<<code[i].ch<<"的权值为:"<<hftree[i].weight<<setw(5)<<"编码为:";
for(int j=code[i].start;j<=n;j++)
cout<<code[i].bits[j]<<" ";
cout<<endl;
}
}
void main()
{
creathuffmantree();
huffcode();
}

搜索更多相关主题的帖子: 哈夫曼 
2007-10-17 18:12



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-178476-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.328653 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved