哈夫曼編碼的實現(讀入檔案的形式)
阿新 • • 發佈:2018-11-27
#include<bits/stdc++.h> using namespace std; int w[30]; typedef struct { int weight; int parent,lchild,rchild; }HTNode,*HuffmanTree; typedef char **HuffmanCode; void Select(HuffmanTree HT,int n,int &s1,int &s2) { int i,min; for (i=1;i<=n;i++) if (HT[i].parent==0) { min = i; break; } for (i=1;i<=n;i++) if (HT[i].parent==0) if (HT[i].weight<HT[min].weight) min = i; s1 = min; for (i=1;i<=n;i++) if (HT[i].parent==0 && i!=s1) { min = i; break; } for (i=1;i<=n;i++) if (HT[i].parent==0 && i!=s1) if (HT[i].weight<HT[min].weight) min = i; s2 = min; } void CreateHuffmanTree(HuffmanTree &HT,int n) { int m,i,s1,s2; if (n<=1) return; m = 2 * n - 1; HT = new HTNode[m+1]; for (i=1;i<=m;i++) { HT[i].parent = 0; HT[i].lchild = 0; HT[i].rchild = 0; } for (i=1;i<=n;i++) HT[i].weight = w[i]; for (i=n+1;i<=m;i++) { Select(HT,i-1,s1,s2); HT[s1].parent = i; HT[s2].parent = i; HT[i].lchild = s1; HT[i].rchild = s2; HT[i].weight = HT[s1].weight + HT[s2].weight; } printf("\n i weight parent lchild rchild \n"); for(int i=1; i<=m; ++i) printf("%2d %5d %8d %8d %8d\n",i,HT[i].weight,HT[i].parent,HT[i].rchild,HT[i].lchild); } void CreatHuffmanCode(HuffmanTree HT,HuffmanCode &HC,int n,int len,char s[]) { HC = new char*[n+1]; char *cd = new char[n]; int i,start,f,c,w = 0; 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; printf(" i Char Code\n\n"); for(int i=1; i<=n; ++i) printf("%2d %c %s\n",i,i+'A'-1,HC[i]); for (int i=0;i<len;i++) printf("%s",HC[s[i]-'A']+1); } int main() { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); char s[1000]; scanf("%s",s); int len = strlen(s); memset(w,0,sizeof(w)); for (int i=0;i<len;i++) w[s[i]-'A'+1]++; int n = 0; for (int i=1;i<=26;i++) if (w[i]) n++; for (int i=1;i<=26;i++) if (w[i]) printf("%c : %d\n",'A'+i-1,w[i]); HuffmanTree HT; HuffmanCode HC; CreateHuffmanTree(HT,n); CreatHuffmanCode(HT,HC,n,len,s); return 0; }