|
发表于 2020-11-1 17:56:30
|
显示全部楼层
#include<iostream>
using namespace std;
typedef struct{
int weight;
int parent,lchild,rchild;
}HTNode,*huffmanTree;
CreatHuffmanTree(HuffmanTree &HT,int n);
void Select(HuffmanTree HT,int m,int &s1,int &s2)
{
min1=min(HT,m);
min2=min(HT,m);
}
int min(HUffmanTree HT,int m)
{
int i=0;
int min;
int min_weight;
while(HT[i].parent!=0)
i++;
min_weight=HT[i].weight;
min=i;
for(;i<m;i++)
{
if(HT[i].weight<min_weight && HT[i].parent==0)
{
min_weight=HT[i].weight;
min=i;
}
}
HT[min].parent=1;
return min;
}
void CreatHuffmanTree(HuffmanTree &HT,int n)
{
if(n<=1) return;
m = 2*n-1;
HT = new HTNode[m+1];
for(int i=1;i<=m;i++)
{
HT[i].parent=0;
HT[i].lchild=0;
HT[i].rchild=0;
}
for(int i=1;i<=n;++i)
cin>>HT[i].weight;
for(k=n+1;i<=m;i++)
{
Select(HT,k-1,s1,s2);
HT[s1].parent=k;
HT[s2].parent=k;
HT[k].lchild=s1;
HT[k].rchild=s2;
HT[k].weight=HT[s1].weight+HT[s2].weight;
}
}
typedef char **HuffmanCode;
void CreatHuffmanCode(Huffman HT,HuffmanCode &HC,int n)
{
HC=new char*[n+1];
cd=new char[n];
cd[n-1]='\0';
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;
}
int main()
{
void Select(HuffmanTree HT,int m,int &s1,int &s2);
int min(HUffmanTree HT,int m);
void CreatHuffmanTree(HuffmanTree &HT,int n);
void CreatHuffmanCode(Huffman HT,HuffmanCode &HC,int n);
int n;
cout<<"请输入结点个数:"<<endl;
cin>>n;
HTNode *Huffman=new HTNode[2*n-1];
int *weight=new int[n];
char **HC=new char*[n];
cout<<"请输入"<<n<<"个权值:";
CreatHuffmanTree(huffmanTree,n);
CreatHuffmanCode(,huffman HT,huffmancode HC,n);
cout<<"输出哈夫曼编码:"<<endl;
}
|
|