哈夫曼编码## 标题
求个大佬帮我看一下我这个为什么运行出来的结果是错的
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include
#include
#define MAX 65535
typedef struct{
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
int n;
typedef char **HuffmanCode;
void select(HuffmanTree HT, int m, int *s1, int *s2){
int min1, min2, a, b,j;
int i=1;
while( HT[i].parent != 0) {
i++;
}
min1=HT[i].weight;
a=i;
for(j=i+1; j<=m; j++)
{
if(min1 > HT[j].weight && HT[j].parent==0)
{
min1=HT[j].weight;
a=j;
}
}
i=1;
while( HT[i].parent != 0 || a==i )
{
i++;
}
min2=HT[i].weight;
b=i;
for(j=i+1; j<=m; j++)
{
if(j==a)
continue;
if(min2 > HT[j].weight && HT[j].parent==0)
{
min2=HT[j].weight;
b=j;
}
}
*s1=a;
*s2=b;
}
void CreateHuffmanTree(HuffmanTree &HT,int t[])//建树
{
int i,m;
int s1,s2;
if(n<=1)
return;
m=2n-1;
HT=new HTNode[m+1];
for(i=1;i<=n;i++)
{
HT[i].weight=t[i-1];
HT[i].parent=0;
HT[i].lchild=0;
HT[i].rchild=0;
}
for(i=n; i<=m; i++)
{
HT[i].weight=0;
HT[i].parent=0;
HT[i].lchild=0;
HT[i].rchild=0; }
for(i=n+1;i<m;++i){
select(HT,i-1,&s1,&s2); HT[s1].parent=i;
HT[s2].parent=i;
HT[i].lchild=s1;
HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight;}
}
void CreatHuffmanCode(HuffmanTree HT,HuffmanCode &HC)//偏码
{
int c,f,start;
int i;
HC=new char[n+1];
char *cd=new char[n];
cd[n-1]=’\0’;
//printf(“字符编码为:”);
for(i=1;i<=n;++i)
{ start=n-1;
c=i;
f=HT[i].parent;
while(f!=0)
{ --start;
if(HT[f].lchild==c)
cd[start]=‘0’;
else
cd[start]=‘1’;
c=f;
f=HT[f].parent; } HC[i]=new char[n-start]; strcpy(HC[i],&cd[start]); }
delete cd;}
void output(HuffmanCode ht,char m[]){
int k;
printf(“字符编码为:\n”);
for(k=1;k<=n;k++)
{
printf(“字符:%c\t”,m[k-1]);
printf(“编码:%s\n”,ht[k]);
}
}
void main()
{
HuffmanTree HT;
HuffmanCode ht;
char a[MAX];//存放字符串
char w[100];//存放字符
int b[100];//存放权值
int i,j;
printf(“请输入一段字符:\n”);
gets(a);
printf("\n");
for (i=0;a[i]!=’\0’;i++)
{ // cout<<n<<"________________"<<endl;
for(j=0; j<n; j++)
{
if (w[j]==a[n])
{
b[j]=b[j]+1;
break;
}
}
if (j>=n) {
w[n]=a[n];
b[n]=1;
n++;
}
}
printf(“信息如下:\n”);
for (i=0;i<n;i++)
{
printf(“字符:%c”,w[i]);
printf(“权值:%d\n”,b[i]);
//cout<<“字符:”<<a[i]<<" 权值:"<<b[i]<<endl; }
CreateHuffmanTree(HT,b); CreatHuffmanCode(HT,ht);
output(ht,w); }