`
gaofen100
  • 浏览: 1189342 次
文章分类
社区版块
存档分类
最新评论

数据结构 树 Huffman编码

 
阅读更多

1. Huffman树不是唯一的,这是因为在选择具有最小权值的2个节点时会出现权值相等的情况。

编码效率是不是一样的?不一样,但相差不大。

如何选择最小的?

2. 一组数,找最小的两个,算法的复杂度是On + ceil(log(n)) - 2),使用堆排序。

3. Huffman编码算法用于压缩。

程序如下:

#include<stdio.h>
#include
<stdlib.h>
#include
<string.h>

typedef
struct...{
unsigned
intweight;
unsigned
intparent;
unsigned
intleft;
unsigned
intright;
}
HNode;

typedef
char**HCode;

voidselect(HNode*htree,inti,int&s1,int&s2)...{
for(intj=1;j<=i;j++)...{
if(htree[j].parent!=0)...{
continue;
}
else...{
s1
=j;
break;
}

}


for(j++;j<=i;j++)...{
if(htree[j].parent!=0)...{
continue;
}
else...{
s2
=j;
break;
}

}


if(htree[s1].weight>htree[s2].weight)...{
inttmp=s2;
s2
=s1;
s1
=tmp;
}


for(j=1;j<=i;j++)...{
if(htree[j].parent==0)...{
if(htree[j].weight<=htree[s2].weight)...{
if(htree[j].weight<htree[s1].weight)...{
s2
=s1;
s1
=j;
}
else...{
if(j!=s1)...{
s2
=j;
}

}

}

}

}

}


voidHuffmanCoding(HNode*htree,HCode&hcode,int*w,intn)...{
if(n<=1)...{
return;
}


intm=2*n-1;
inti=0;

htree
=(HNode*)malloc(sizeof(HNode)*(m+1));

HNode
*p=htree;
for(i=1;i<=n;i++)...{
p
++;

(
*p).weight=w[i-1];

(
*p).parent=(*p).left=(*p).right=0;
}


for(;i<=m;i++)...{
p
++;
(
*p).weight=(*p).parent=(*p).left=(*p).right=0;
}



ints1=0,s2=0;
for(i=n+1;i<=m;i++)...{
select(htree,i
-1,s1,s2);
htree[s1].parent
=i;
htree[s2].parent
=i;
htree[i].left
=s1;
htree[i].right
=s2;
htree[i].weight
=htree[s1].weight+htree[s2].weight;
}



hcode
=(HCode)malloc(sizeof(char*)*(n+1));

char*ch=(char*)malloc(n*sizeof(char));
ch[n
-1]='

执行结果为:

Huffman编码为:
a:
11111
b:
10
c:
1110
d:
000
e:
110
f:
01
g:
11110
h:
001
1111110000110
abde
Pressanykeyto
continue
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics