帮下忙看下那里错拉 c语言

// 实验七  赫夫曼编码.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define MaxValue 10000
#define MaxBit 4
#define MaxN 10

typedef struct{
 int weight,flag;
 int parent,lchild,rchild;
}HTNode;

typedef struct{
 int bit[MaxN];
 int start;
 int weight;
}Code;

void Haffman(int weight[],int n,HTNode haffTree[])
{
 int i,j,m1,m2,x1,x2;
 for(i=0;i<2*n-1;i++){
  if(i<n)
   haffTree[i].weight=weight[i];
  else
   haffTree[i].weight=0;
  haffTree[i].parent=-1;
  haffTree[i].flag=0;
  haffTree[i].lchild=-1;
  haffTree[i].rchild=-1;
 }
 for(i=0;i<n-1;i++)
 {
  m1=m2=MaxValue;
  x1=x2=0;
  for(j=0;j<n+1;j++)
  {
   if(haffTree[j].weight<m1&&haffTree[j].flag==0)
   {
    m2=m1;
    x2=x1;
    m1=haffTree[j].weight;
    x1=j;
   }
   else if(haffTree[j].weight<m2&&haffTree[j].flag==0){
    m2=haffTree[j].weight;
    x2=j;
   }
  }
  haffTree[x1].parent=n+i;
  haffTree[x2].parent=n+i;
  haffTree[x1].flag=1;
  haffTree[x2].flag=1;
  haffTree[n+i].weight=haffTree[x1].weight+haffTree[x2].weight;
  haffTree[n+i].lchild=x1;
  haffTree[n+i].rchild=x2;
 }
}


void HaffmanCode(HTNode haffTree[],int n,Code haffCode[])
{
 Code *cd=(Code *)malloc(sizeof(Code));
 int i,j,child,parent;
 for (i=0;i<n;i++)
 {
  cd->start=n-1;
  cd->weight=haffTree[i].weight;
  child=i;
  parent=haffTree[child].parent;
  while(parent!=-1)
  {
   if(haffTree[parent].lchild==child)
    cd->bit[cd->start]=0;
   else cd->bit[cd->start]=1;
   cd->start--;
   child=parent;
   parent=haffTree[child].parent;
  }
  for(j=cd->start+1;j<n;j++)
   haffCode[i].bit[j]=cd->bit[j];
  haffCode[i].start=cd->start+1;
  haffCode[i].weight=cd->weight;
 }
}

 

 


void main()
{
 int i,j,n=4;
 int weight[]={1,3,5,7};
 HTNode *myHaffTree=(HTNode *)malloc(sizeof(HTNode)*(2*n+1));
 Code *myHaffCode=(Code *)malloc(sizeof(Code)*n);
 if(n>MaxN)
 {
  printf("给出的 N越界!/n");
 }
 Haffman(weight,n,myHaffTree);
 HaffmanCode(myHaffTree,n,myHaffCode);
 for(i=0;i<n;i++)
 {
  printf("Weight=%d Code=",myHaffCode[i].weight);
  for(j=myHaffCode[i].start;j<n;j++)
   printf("%d",myHaffCode[i].bit[j]);
  printf("/n");
 }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITbingge

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值