数据结构(第二版) 严蔚敏
#include<iostream> #include<cstring> #include<algorithm> using namespace std; #define inf 9999999 int n,m; typedef char **huffmancode; typedef struct { int weigth; int parent, lchild, rchild; }htnode, *huffmantree; void Select(huffmantree &ht,int s,int &s1,int &s2) { s1=s2=0; int min1,min2; min1=min2=inf; for(int j=1;j<=s;j++) if(ht[j].parent==0) { if(ht[j].weigth<=min1) { min2=min1; min1=ht[j].weigth; s2=s1;s1=j; } else if(ht[j].weigth<=min2) { min2=ht[j].weigth; s2=j; } } } void createhuffmantree(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].weigth; for (int i = n + 1; i <= m; i++) { int s1,s2; Select(ht,i-1,s1,s2); ht[s1].parent = i; ht[s2].parent = i; ht[i].lchild = s1; ht[i].rchild = s2; ht[i].weigth = ht[s1].weigth+ ht[s2].weigth; } } void createhuffmancode(huffmantree &ht,huffmancode &hc,int n) { hc=new char*[n+1]; char *cd=new char[n]; for(int i=1;i<=n;i++) { int start=n-1,c=i,f=ht[i].parent; while(f!=0) { --start; if(ht[f].lchild==c) cd[start]='0'; else cd[start]='l'; c=f;f=ht[f].parent; } hc[i]=new char[n-start];strcpy(hc[i],&cd[start]); }delete cd; } int main() { cout<<"请输入叶子结点数目(n>1):"<<endl; cin>>n; cout<<"请输入权值"<<endl; huffmantree ht; huffmancode hc; createhuffmantree(ht,n); for(int i=1;i<=m;i++) { cout<<ht[i].weigth<<' '; } cout<<endl; createhuffmancode(ht,hc,n); for(int i=1;i<=n;i++) { cout<<ht[i].weigth<<' '<<hc[i]<<endl; } delete ht; }