1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std;
#define N 100 #define M (2*N-1)
struct HTNode{ unsigned int weight; unsigned int parent,lchild,rchild; };
struct HTCode{ char data; int weight; char code[N]; };
void init_huffman(HTCode hc[], int k) { int i; printf("please input %d characters:\n", k); for(i = 1; i <= k; i++) scanf("%c", &hc[i].data); printf("\nplease input %d weights:\n", k); for(i = 1; i <= k-1; i++) scanf("%d",&hc[i].weight); scanf("%d", &hc[i].weight); }
void select(HTNode ht[], int k, int *s1, int *s2) { int i; for(i = 1; i <= k && ht[i].parent != 0; i++) ; *s1 = i; for(i = 1; i <= k; i++) { if(ht[i].parent == 0 && ht[i].weight < ht[*s1].weight) *s1 = i; }
for(i = 1; i <= k ; i++) { if(ht[i].parent == 0 && i != *s1) break; } *s2 = i; for(i = 1; i <= k; i++) { if(ht[i].parent == 0 && i != *s1 && ht[i].weight < ht[*s2].weight) *s2 = i; } }
void HuffmanCoding(HTNode ht[], HTCode hc[], int n) { int s1, s2, c, f, start; int m = 2 * n - 1; int i; if(n <= 1) return ; for(i = 1; i <= m; i++) { if(i <= n) ht[i].weight = hc[i].weight; ht[i].parent = ht[i].lchild = ht[i].rchild = 0; } for(i = n + 1; i <= m; i++) { select(ht, i - 1, &s1, &s2); ht[s1].parent = ht[s2].parent = i; ht[i].lchild = s1; ht[i].rchild = s2; ht[i].weight = ht[s1].weight + ht[s2].weight; } char cd[n]; cd[n-1] = '\0'; for(i = 1; i <= n; i++) { start = n - 1; for(c = i, f = ht[i].parent; f!=0; c=f,f=ht[f].parent) { if(ht[f].lchild == c) cd[--start] = '0'; else cd[--start] = '1'; } strcpy(hc[i].code, &cd[start]); } }
int main() { int n; printf("please input n = "); scanf("%d",&n); getchar();
HTNode ht[2*n-1 + 1]; HTCode hc[n + 1]; init_huffman(hc, n); HuffmanCoding(ht, hc, n);
for(int i = 1; i <= n; i++) printf("\n%c---%s\n", hc[i].data, hc[i].code); return 0; }
|