#include<iostream.h>
#include<string.h>
#define N 100
typedef struct
{
int wei //权值
int prt //父节点
int lch //左子节点
int rch// 右子节点
int tmp //中间变量,tmp=0 还未进行遍历 tmp=1 已近进行过向左遍历 tmp=2 已经进行过左右遍历 向上找到节点
char code[N]
}huffmantree
void input()
void print(huffmantree )
void select(huffmantree *HT,int n,int &i,int &j)
{
int k
i=1
while(HT[i].prt!=0)
{
i++
}
for(k=i+1k<=nk++)
{
if((HT[k].prt=0)&&(HT[k].wei <HT[i].wei))
i=k
}
j=1
while((j==i)||(HT[j].prt!=0))
{
j++
}
for(k=j+1k<=nk++)
{
if((HT[k].prt=0)&&k!=i&&HT[k].wei<HT[j].wei)
j=k
}
}
void huffman(int w[],huffmantree *HT,int n) //w存放n个字符的权值
{
int m=2*n-1
int i,k,j
huffmantree *p=0
for(p=HT+1,i=1i<=mi++,p++)
{
HT[i].prt=0
HT[i].lch=0
HT[i].rch=0
}
for(p=HT+1,i=1i<=ni++,p++)
{
HT[i].wei=w[i-1]
}
for(p=HT+n+1,i=n+1i<=mi++,p++)
{ HT[i].wei=0}
for(k=n+1k<=mk++)
{
select(HT,k-1,i,j) // 找最小值和次小值的位置
HT[i].prt=k,HT[j].prt=k // 找到i j 的父节点付给k
HT[k].lch=i,HT[k].rch=j // 父节点的左右指针分别指向i, j
HT[k].wei=HT[i].wei+HT[j].wei
}
}
void huffmancoding(huffmantree *HT,int n) //n个叶子结点的huffman编码 从根节点开始编码
{
int BT=2*n-1
int m=BT
int l,r,p
char s1[100]="0",s2[100]="1"
for(int i=0i<=mi++)//中间变量赋初值
{ HT[i].tmp=0 }
strcpy(HT[m].code," ")
while(1)
{
l=HT[BT].lch
r=HT[BT].rch
p=HT[BT].prt
if(p==0&&HT[BT].tmp==2)
break
if(l==0||r==0)
{
HT[BT].tmp=2//如果是叶子结点则给中间变量赋值2向上返回一节结点
}
if(HT[BT].tmp==0) //未进行过遍历,开始向左遍历
{
HT[BT].tmp=1 //已经进行过向左遍历
l=HT[BT].lch
strcpy(HT[l].code,HT[BT].code)
strcat(HT[l].code,s1)
BT=l
}
else
if(HT[BT].tmp==1)
{
HT[BT].tmp=2
r=HT[BT].rch
strcpy(HT[r].code,HT[BT].code)
strcat(HT[r].code,s2)
BT=r
}
else if(HT[BT].tmp==2)
{
p=HT[BT].prt
BT=p
}
}
}
void print(huffmantree HT[],int n) //总共n个叶子节点
{
int i
cout<<"源码:"<<endl
for(i=1i<=ni++)
cout<<HT[i].wei<<endl
cout<<"Huffman编码:"<<endl
for(i=1i<=ni++)
{
cout<<HT[i].code<<endl
}
}
void input(int w[],int n)
{
int t,*p
int i=0
cout<<"对应的输入源码出现权值:(以-1结束)"<<endl
cin>>t
while(t>=0)
{
p=new int
*p=t
w[i]=*p
i++
cin>>t
}
}
void main()
{
int n,m
cout<<"输入源码个数:"
cin>>n
int *w
w=new int[n+1]
input(w,n)
m=2*n-1
huffmantree *HT
HT=new huffmantree[m+1]
huffman(w,HT,n)
huffmancoding(HT,n)
print(HT,n)
delete w,HT
}
Matlab自带Huffman函数(ps:你拼写错了)huffmandeco Huffman decoder
huffmandict Generate Huffman code dictionary for a source with known probability model
huffmanenco Huffman encoder
密码生成:
symbols = [1 2 3]% Data symbols
p = [0.1 0.1 0.8]% Probability of each data symbol
dict = huffmandict(symbols,p) % Create the dictionary.
dict{1,:} % Show one row of the dictionary.
加密解密:
sig = repmat([3 3 1 3 3 3 3 3 2 3],1,50)% Data to encode
symbols = [1 2 3]% Distinct data symbols appearing in sig
p = [0.1 0.1 0.8]% Probability of each data symbol
dict = huffmandict(symbols,p)% Create the dictionary.
hcode = huffmanenco(sig,dict)% Encode the data.
dhsig = huffmandeco(hcode,dict)% Decode the code.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)