第1个回答 推荐于2016-05-23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define n 8
#define m 2*n-1
#define max 2000
typedef struct
{
int wi;
char data;
int Parent,Lchild,Rchild;
}huffm;
huffm HT[m+1];
typedef struct
{
char bits[n+1];
int start;
char ch;
}ctype;
void HuffmTree(huffm HT[m+1]);
void Huffmcode(ctype code[n+1]);
void Output (ctype code[n+1]);
/* 构造HuffmTree的函数*/
void HuffmTree(huffm *HT)
{
int i,j,p1,p2;
int s1,s2;
// for(i=1;i<=n;i++)
// {
// scanf("%d",&w);
// HT[i].wi = w;
// }
for(i=n+1;i<=m;i++)
{
p1=p2=0;
s1=s2=max;
for(j=1;j<=i-1;j++)
if(HT[j].Parent ==0)
if(HT[j].wi <s1)
{
s2=s1;
s1=HT[j].wi;
p2=p1; p1=j;
}
else if(HT[j].wi<s2)
{
s2=HT[j].wi ;
p2=j;
}
HT[p1].Parent = HT[p2].Parent =i;
HT[i].Lchild =p1;
HT[i].Rchild =p2;
HT[i].wi =HT[p1].wi + HT[p2].wi ;
}
// printf("\n OK!");
// for(i=1;i<=m;i++)
// {
// printf("\n");
// printf("%d ",HT[i].wi);
// }
// getchar();
return ;
}
/* 求HuffmTree编码的函数*/
void Huffmcode(ctype code[n+1])
{
int i,p,s;
ctype md;
for(i=1;i<=n;i++)
{
md.ch = code[i].ch;
md.start = n+1;
s = i;
p = HT[i].Parent;
while(p!=0)
{
md.start--;
if(HT[p].Lchild ==s)
md.bits[md.start]='0';
else
md.bits[md.start] ='1';
s=p;
p=HT[p].Parent;
}
code[i] = md;
}
}
/*打印编码函数*/
void Output(ctype code[n+1])
{
int i,j;
for(i=1;i<=n;i++)
{
printf("\n");
printf("%c ",code[i].ch );
for(j=1;j<=8;j++)
{
if(j<code[i].start)
printf(" ");
else
if((code[i].bits[j] == '0')||(code[i].bits[j] == '1'))
printf("%c",code[i].bits[j]);
}
printf(" %d",code[i].start);
}
}
void main()
{
int i,j;
int w;
int flag=1;
int choice;
ctype code[n+1];
char temp[n+1];
int temp2[n+1];
printf("Would you want to play?(1-Yes and Start/0-No and Exit)");
scanf("%d",&choice);
while(flag&&(choice==1))
{
choice = 0;
for(i=1;i<=m;i++)//初始化
{
HT[i].data =NULL;
HT[i].wi=0;
HT[i].Parent = 0;
HT[i].Lchild = HT[i].Rchild = 0;
}
for(i=1;i<=n;i++)
{
code[i].start = 0;
code[i].ch = NULL;
for(j=1;j<=n;j++)
code[i].bits[j] = NULL;
}
printf("Please input %d char: \n",n);
getchar();
scanf("%c %c %c %c %c %c %c %c",&temp[1],&temp[2],&temp[3],&temp[4],&temp[5],&temp[6],&temp[7],&temp[8]);
for(i=1;i<=n;i++)
{
// scanf("%c",&w);
code[i].ch =temp[i];
HT[i].data =temp[i];
}
printf("Please input %d rate: \n",n);
getchar();
scanf("%d %d %d %d %d %d %d %d",&temp2[1],&temp2[2],&temp2[3],&temp2[4],&temp2[5],&temp2[6],&temp2[7],&temp2[8]);
for(i=1;i<=n;i++)
{
//scanf("%d",&w);
w= temp2[i];
HT[i].wi = w;
}
HuffmTree(HT);
Huffmcode(code);
Output(code);
printf("\nContinue?1-Contine,0-Exit\n");
scanf("%d",&choice);
if(choice!=1)
break;
}
getchar();
return;
}
运行过,正确的本回答被网友采纳