huffman
#include <stdio.h> #include <string.h> #define n 5 #define m (2*n-1) typedef struct{ int weight; int lchild,rchild,parent; }HTNode; typedef HTNode HuffmanTree[m]; void InitHuffmanTree(HuffmanTree ht){ for(int i=0;i<m;++i){ ht[i].parent=ht[i].lchild=ht[i].rchild=-1; } printf("init done\n"); } void InputWeight(HuffmanTree ht){ for(int i=0;i<n;++i){ scanf("%d",&ht[i].weight); } printf("input done\n"); } void CreateHT(HuffmanTree ht){ InitHuffmanTree(ht); InputWeight(ht); int min1,min2,lnode,rnode,k; for(int i=n;i<m;++i){ min1=min2=32767; lnode=rnode=-1; for(k=0;k<i-1;++k){ if(ht[k].parent==-1){ if(ht[k].parent==-1){ if(ht[k].weight<min1){ min2=min1; rnode=lnode; min1=ht[k].weight; lnode=k; } else if(ht[k].weight<min2){ min2=ht[k].weight; rnode=k; } } } } ht[lnode].parent=i; ht[rnode].parent=i; ht[i].lchild=lnode; ht[i].rchild=rnode; ht[i].weight=ht[lnode].weight+ht[rnode].weight; } } typedef struct { char ch; char bits[n+1]; }CodeNode; typedef CodeNode HuffmanCode[n]; void CharSetHuffmanEncoding(HuffmanTree T,HuffmanCode H) { int c,p,i; char cd[n+1]; int start; cd[n]='\0'; for(i=0;i<n;++i){ H[i].ch=getchar(); start=n; c=i; while((p=T[c].parent)>=0){ cd[--start]=(T[p].lchild==c)?'0':'1'; c=p; //继续上溯 } strcpy(H[i].bits,&cd[start]); } }