1、某通讯系统只使用6种字符a、e、r、t、d、f,其使用频率分别为8, 4, 6,
3, 1, 1,利用赫夫曼树设计一种前缀编码。
2、使用上题中设计的前缀编码,分别对通讯信号“01011101111100011”和“0101011010”进行译码。
1、某通讯系统只使用6种字符a、e、r、t、d、f,其使用频率分别为8, 4, 6,
3, 1, 1,利用赫夫曼树设计一种前缀编码。
2、使用上题中设计的前缀编码,分别对通讯信号“01011101111100011”和“0101011010”进行译码。
写了个代码,测试了一下,"0101011010"这个串不能正确译码,是不是题干有误?
#include "stdafx.h"
// Huffman.cpp : 定义控制台应用程序的入口点。
#include <stdio.h>
#include <string.h>
#define N 50
#define M 2*N-1
typedef struct
{
char data[5];
int weight;
int parent;
int lchild;
int rchild;
} HTNode;
typedef struct
{
char cd[N];
int start;
} HCode;
void CreateHT(HTNode ht[],int n)
{
int i,k,lnode,rnode;
int min1,min2;
for (i=0;i<2*n-1;i++)
ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
for (i=n;i<2*n-1;i++)
{
min1=min2=32767;
lnode=rnode=-1;
for (k=0;k<=i-1;k++)
if (ht[k].parent==-1)
{
if (ht[k].weight<min1)
{
min2=min1;rnode=lnode;
min1=ht[k].weight;lnode=k;
}
else if (ht[k].weight<min2)
{
min2=ht[k].weight;rnode=k;
}
}
ht[lnode].parent=i;ht[rnode].parent=i;
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;ht[i].rchild=rnode;
}
}
void CreateHCode(HTNode ht[],HCode hcd[],int n)
{
int i,f,c;
HCode hc;
for (i=0;i<n;i++)
{
hc.start=n;c=i;
f=ht[i].parent;
while (f!=-1)
{
if (ht[f].lchild==c)
hc.cd[hc.start--]='0';
else
hc.cd[hc.start--]='1';
c=f;f=ht[f].parent;
}
hc.start++;
hcd[i]=hc;
}
}
void DispHCode(HTNode ht[],HCode hcd[],int n)
{
int i,k;
int sum=0,m=0,j;
printf(" 输出哈夫曼编码:\n");
for (i=0;i<n;i++)
{
j=0;
printf(" %s:\t",ht[i].data);
for (k=hcd[i].start;k<=n;k++)
{
printf("%c",hcd[i].cd[k]);
j++;
}
m+=ht[i].weight;
sum+=ht[i].weight*j;
printf("\n");
}
printf("\n 平均长度=%g\n",1.0*sum/m);
}
int findsubstr(char* S, int cS, HCode hcd[],int n, int &pos)
{
int i,k, j;
if (pos > cS) return -1;
for (i=0;i<n;i++)
{
j = pos;
for (k=hcd[i].start;k<=n;k++)
{
if (S[j] == hcd[i].cd[k])
j++;
else
break;
}
if (k > n)
{
pos = j;
return i;
}
}
return -1;
}
bool Recode(char* S, int cS, HTNode ht[],HCode hcd[],int n){
char strresult[80];
strcpy(strresult,"");
int pos = 0;
while (pos < cS)
{
int result = findsubstr(S, cS, hcd, n, pos);
if (result != -1)
{
strcat(strresult, ht[result].data);
}
else
return false;
}
printf("译码结果为:%s\n\n", strresult);
return true;
}
void main()
{
int i, n=6;
// char *str[]={"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
// int fnum[]={1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
char *str[]={"a","e","r","t","d","f"};
int fnum[]={8,4,6,3,1,1};
HTNode ht[M];
HCode hcd[N];
for (i=0; i<n; i++)
{
strcpy(ht[i].data, str[i]);
ht[i].weight=fnum[i];
}
printf("\n");
CreateHT(ht,n);
CreateHCode(ht,hcd,n);
DispHCode(ht,hcd,n);
printf("\n");
char* strtest1="01011101111100011";
printf("破译原文是:%s\n", strtest1);
int clength = strlen(strtest1);
if (!Recode(strtest1, clength, ht, hcd, n))
printf("译密失败\n");
char* strtest2="0101011010";
printf("破译原文是:%s\n", strtest2);
clength = strlen(strtest2);
if (!Recode(strtest2, clength, ht, hcd, n))
printf("译密失败\n");
system("pause");
}