霍夫曼树建树初步
漏掉了huffman树,赶紧来一发.
huffman:构建最小带权二叉树,算法思想为贪心.
hdu1053
#include <algorithm> #include <functional> using namespace std; struct tree { tree* prent; tree* l; tree* r; int val; char chr; tree() { this->val=0; this->chr=0; this->l=NULL; this->r=NULL; } }; int sortcmp(const void *p1, const void *p2) { tree** t1=(tree**)p1; tree** t2=(tree**)p2; return (*t1)->val-(*t2)->val; } tree* create(int val,char chr,tree* l,tree* r) { tree* t = new tree(); t->val=val; t->chr=chr; t->l=l; t->r=r; return t; } void del(tree* t) { if(t->l) { del(t->l); } if(t->r) { del(t->r); } delete t; } int sub(tree* t,int* h,int c) { c++; int sum=0; if(t->l!=NULL) { sum+=sub(t->l,h,c); } if(t->r!=NULL) { sum+=sub(t->r,h,c); } if(t->chr>0); { sum+=c*h[t->chr]; } return sum; } int main() { char str[1024]={0}; while(scanf("%s",str)!=EOF && strcmp(str,"END")!=0) { int huff[255]={0}; for(int i=0;i<strlen(str);i++) { huff[str[i]]++; } tree* q[10240]; int h=0,f=0; for(int i=0;i<255;i++) { if(huff[i]) { q[f++]=create(huff[i],i,NULL,NULL); } } while(f-h>1) { qsort(&q[h],f-h,sizeof(tree*),sortcmp); q[f++]=create(q[h]->val+q[h+1]->val,0,q[h],q[h+1]); h+=2; } int newlen = sub(q[f-1],huff,-1); if(newlen==0) { newlen=strlen(str);//hack } printf("%d %d %.1lf\n",strlen(str)*8,newlen,strlen(str)*8.0/newlen); del(q[f-1]); memset(str,0,sizeof(str)); } //system("pause"); return 0; }