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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include<stdio.h> #define n 5 #define m (2*n-1) #define maxval 10000.0 #define maxsize 100
typedef struct{ char ch; float weight; int lchild,rchild,parent; }hufmtree;
typedef struct{ char bits[n]; int start; char ch; }codetype;
void huffman(hufmtree tree[]){ int i,j,p1,p2; float small1,small2,f; char c; for(i=0;i<m;i++){ tree[i].parent=0; tree[i].lchild=-1; tree[i].rchild=-1; tree[i].weight=0.0; } for(i=0;i<n;i++){ printf("输入第%d个字符为和权值:",i+1); scanf("%c %f",&c,&f); getchar(); tree[i].ch=c; tree[i].weight=f; } for(i=n;i<m;i++){ p1=0;p2=0; small1=maxval;small2=maxval; for(j=0;j<i;j++) if(tree[j].parent==0) if(tree[j].weight<small1){ small2=small1; small1=tree[j].weight; p2=p1; p1=j; }else if(tree[j].weight<small2){ small2=tree[j].weight; p2=j; } tree[p1].parent=i; tree[p2].parent=i; tree[i].lchild=p1; tree[i].rchild=p2; tree[i].weight=tree[p1].weight+tree[p2].weight; } }
void huffmancode(codetype code[],hufmtree tree[]){ int i,c,p; codetype cd; for(i=0;i<n;i++){ cd.start=n; cd.ch=tree[i].ch; c=i; p=tree[i].parent; while(p!=0){ cd.start--; if(tree[p].lchild==c) cd.bits[cd.start]='0'; else cd.bits[cd.start]='1'; c=p; p=tree[p].parent; } code[i]=cd; } }
void decode(hufmtree tree[]){ int i,j; char b[maxsize]; i=m-1; printf("输入发送的编码(以'#'为结束标志):"); gets(b); printf("译码后的字符为"); for(j=0;b[j]!='#';j++){ if(b[j]=='0') i=tree[i].lchild; else i=tree[i].rchild; if(tree[i].lchild==-1) { printf("%c",tree[i].ch); i=m-1; } } if(tree[i].lchild!=-1 && b[j]!= '#') printf("\nERROR\n"); }
void input(hufmtree tree[],codetype code[]){ int i,j; printf("【哈夫曼编码】\n"); printf("总共有%d个字符\n",n); huffman(tree); huffmancode(code,tree); printf("【输出每个字符的哈夫曼编码】\n"); for(i=0;i<n;i++){ printf("%c: ",code[i].ch); for(j=code[i].start;j<n;j++) printf("%c",code[i].bits[j]); printf("\n"); } }
int main(){ hufmtree tree[m]; codetype code[n]; input(tree,code);
printf("【哈夫曼译码】\n"); decode(tree); return 0; }
|