近在学哈夫曼树,遇到一个程序,在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();
}
[求助]哈夫曼数的问题