hdu 1053 哈夫曼树/编码

来源:互联网 发布:逆战移动网络延迟 编辑:程序博客网 时间:2024/04/28 10:09

http://acm.hdu.edu.cn/showproblem.php?pid=1053

主要利用哈夫曼编码原理,再加广度有限搜索,思想想出来了~可BUG找了好长时间!!用队列的时候不能用node ,要用node *见下,还要注意字符串全部相同的情况;

#include <iostream>#include <cstdio>#include <queue>#include <string.h>using namespace std;struct node{    char word;    node *lchild,*rchild;    int d;  //根到此节点的距离;    int w;    node():word(0),lchild(0),rchild(0),d(0),w(0){}};struct cmp{bool operator()(node * lhs,node * rhs){    return lhs->w>rhs->w;}};char str[100000];int count1[50];int main(){    while(scanf("%s",str))    {        if(strcmp(str,"END")==0)            break;        int l=strlen(str);        memset(count1,0,sizeof(count1));        for(int i=0;i<l;i++)            count1[str[i]-'A']++;        priority_queue<node*,vector<node*>,cmp> q;        int n=0;        for(int i=0;i<50;i++)        {            if(count1[i])            {                n++;                node *t=new node;                t->word=i+'A';                t->w=count1[i];                q.push(t);            }        }        int flag=0;        if(n==1)            flag=1;        for(int i=0;i<n-1;i++)        {            node *t1=q.top();         //假如用node的话,则for结束则t1就没了!在栈上的被内存收回~            q.pop();            node *t2=q.top();            q.pop();            node *t=new node;            t->lchild=t1;            t->rchild=t2;            t->w=t1->w+t2->w;            q.push(t);        }        node *t=q.top();        q.pop();        int sum=0;        queue<node*> qq;        qq.push(t);        while(!qq.empty())        {            node *u=qq.front();            qq.pop();            if(u->lchild)            {                u->lchild->d=u->d+1;                qq.push(u->lchild);            }            if(u->rchild)            {                u->rchild->d=u->d+1;                qq.push(u->rchild);            }            if(!u->lchild&&!u->rchild)            {                sum+=u->d*count1[u->word-'A'];            }        }        if(flag)            printf("%d %d %.1f\n",l*8,l,(double)l*8/l);        else            printf("%d %d %.1f\n",l*8,sum,(double)l*8/sum);    }    return 0;}



原创粉丝点击