C++哈夫曼编码出错,搞了一个下午,求大神教下

u010413585 2013-08-16 05:12:49
#include<iostream.h>
static tipping_point=0;
struct HaffNode
{
int weight;
int parent;
int lchild;
int rchild;
};
struct HaffCode
{
int bt[10000];
int start;
int weight;
};
void Select(HaffNode ht[],int &x1,int &x2,int n)//选选择权值最小的
{
int m1=1000,m2=1000;
x1=x2=0;
for(int j=0;j<n+tipping_point;j++)
{
// cout<<"X"<<endl;
if(ht[j].weight<m1 && ht[j].parent==-1)//把最小的权值放在x1
{
// cout<<"Y"<<endl;
m2=m1;
x2=x1;
m1=ht[j].weight;
x1=j;
}
else if(ht[j].weight<m2 && ht[j].parent==-1)//把第二小的权值放在x2
{
// cout<<"Z"<<endl;
m2=ht[j].weight;
x2=j;
}
// cout<<"999"<<endl;
}
// cout<<ht[x1].weight<<endl;
// cout<<ht[x2].weight<<endl;
}
void Haffman(int w[],int n,HaffNode ht[])//生成一棵哈夫曼树
{
int i,k;
int i1=0,i2=0;
for(i=0;i<2*n-1;i++)//初始化哈夫曼树
{
if(i<n)
{
ht[i].weight=w[i];
}
else
{
ht[i].weight=0;
}
ht[i].parent=-1;
ht[i].lchild=-1;
ht[i].rchild=-1;
}
for(k=n;k<2*n-1;k++)//构造哈夫曼树
{
Select(ht,i1,i2,n);
tipping_point++;

ht[i1].parent=k;
ht[i2].parent=k;

// cout<<ht[i1].weight<<endl;
// cout<<ht[i2].weight<<endl;

ht[k].weight=ht[i1].weight+ht[i2].weight;
ht[k].lchild=i1;
ht[k].rchild=i2;
}
}
void Haffman_BianMa(HaffNode ht[],int n,HaffCode hc[])//哈夫曼编码
{
HaffCode example;
int child,parent;
for(int i=0;i<n;i++)
{
example.start = 0;//从叶子开始返回根节点
example.weight = ht[i].weight;//存储叶子的权值
child=i;//孩子下标
parent=ht[child].parent;//双亲下标
while(parent!=-1)
{
if(ht[parent].lchild==child)
example.bt[example.start]=0;
else
example.bt[example.start]=1;
example.start--;
child=parent;
parent=ht[child].parent;
}
for(int j=example.start+1;j<n;j++)
{
hc[i].bt[j]=example.bt[j];
}

hc[i].start=example.start;
hc[i].weight=example.weight;
cout<<hc[i].weight<<endl;
// cout<<hc[i].bt[1]<<endl;
}
}
void main()
{
int w[1000];
int n,i,j,a;
cout<<"输入带权值叶子的个数:"<<endl;
cin>>n;
cout<<"输入每个带权值叶子的权值:"<<endl;
for(a=0;a<n;a++)
{
cout<<"请输入第"<<a+1<<"个权值"<<endl;
cin>>w[a];
}
HaffNode* ht=new HaffNode[2*n-1];
HaffCode* hc=new HaffCode[n];
Haffman(w,n,ht);//生成一棵哈夫曼树
Haffman_BianMa(ht,n,hc);//哈夫曼编码
// cout<<hc[0].weight<<endl;
for(i=0;i<n;i++)
{
cout<<"权值weight="<<hc[i].weight<<" 编码code=";
for(j=hc[i].start+1;j<n;j++)
{
cout<<hc[i].bt[j];
}
cout<<endl;
}
}
最后一步输出的权值不对,编码也不对,但是在上面函数中逐步输出时候权值没错,但是编码一样乱,不知道哪里搞错了。特来请教大神
...全文
139 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010413585 2013-08-16
  • 打赏
  • 举报
回复
我思路没错吧,不过自己看自己代码,看来看去都看不出问题
woshinia 2013-08-16
  • 打赏
  • 举报
回复
照着哈夫曼编码规则,再从头到尾过一遍吧,这种东西就讲究逻辑清晰,没什么技术含量的。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧