⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 huffmant.cpp

📁 霍夫曼编码
💻 CPP
字号:

#include "stdafx.h"
#include "fuffmant.h"
#include "string.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif



huffmant::huffmant(huffmantree &h1,huffmancode &h2)
{
HT=h1; HC=h2;
}

void huffmant::makehuffman(int *w,int n)
{
 //float m1,m2;
 int m,m1,m2,i,j,x1,x2,start,f,c;
   //int	 x1,x2,i,j,start,c,f;
 huffmantree p;
 if(n<=1) return ;
 m=2*n-1;
  
 for(p=HT,i=0;i<n;++i,++p,++w)
  {
   p->weight=*w;p->parent=0;
   p->left=0;p->right=0;
  }
 
  for(;i<m;++i,++p)
  {
   p->weight=0;p->parent=0;
   p->left=0;p->right=0;
  }

  for(i=n;i<m;i++)
  {
   m1=m2=MaxV;
   x1=x2=0;
   for(j=0;j<i;j++)
   {
	   if(HT[j].weight<=m1&&HT[j].parent==0)
	   {
        m2=m1; x2=x1;
		m1=HT[j].weight;
		x1=j;
	   }
	   else 
		   if(HT[j].weight<=m2&&HT[j].parent==0)
		   {
		    m2=HT[j].weight;
			x2=j;
		   }
   }

   HT[x1].parent=i; HT[x2].parent=i;
   HT[i].left=x1; HT[i].right=x2;
   HT[i].weight=HT[x1].weight+HT[x2].weight;
  }

  char *cd=(char *)malloc(n*sizeof(char));
  cd[n-1]='\0';
  for(i=0;i<n;i++)
  {
   start=n-1;
   for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
	   if(HT[f].left==c)  cd[--start]='0';
	   else
		   cd[--start]='1';
	   HC[i]=(char *)malloc((n-start)*sizeof(char));
	   strcpy(HC[i],&cd[start]);

  }
  free(cd);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -