Huffman 编码

来源:互联网 发布:淘宝店铺模板装修教程 编辑:程序博客网 时间:2024/04/30 01:03
#include<iostream>#include<cstring>#include<stdlib.h>#include<stdio.h> using namespace std;const int N=1000;int WPL;int n;int W[N];struct node{int w;struct node *rson;struct node *lson;}; struct forest{struct forest *next;struct node *root;};forest *PutIntoForset(forest* f,node* t){forest *pre,*cur,*r;node *ti;r=(forest*)malloc(sizeof(forest));r->root=t;pre=f;cur=f->next;while(cur!=NULL){ti=cur->root;if(t->w>ti->w){pre=cur;cur=cur->next;}else break;}r->next=pre->next;pre->next=r;return f;}node *Huffman(forest* f){forest *fst,*sec;node *t,*uni;while((f->next)!=NULL&&((f->next)->next)!=NULL){fst=f->next;sec=fst->next;f->next=sec->next;uni=(node*)malloc(sizeof(node));uni->w=(fst->root)->w+(sec->root)->w;uni->lson=fst->root;uni->rson=sec->root;free(fst);free(sec);f=PutIntoForset(f,uni);}t=(f->next)->root;free(f);return t;}node *InitHuffman(){WPL=0;struct forest *f;struct node *t;f=(forest*)malloc(sizeof(forest));f->next=NULL;for(int i=0;i<n;i++){t=(node*)malloc(sizeof(node));t->w=W[i];t->rson=NULL;t->lson=NULL;f=PutIntoForset(f,t);}return Huffman(f);}void View(node *head,int steps){if(head!=NULL){if(head->lson==NULL&&head->rson==NULL){WPL+=steps*(head->w);}View(head->lson,steps+1);View(head->rson,steps+1);}}int main(){while(cin>>n)//当只有一个值的时候需要特判 {for(int i=0;i<n;i++){cin>>W[i];}struct node *t;t=InitHuffman();View(t,0);cout<<WPL<<endl;}return 0;}

1 0
原创粉丝点击