hdu 1053 哈夫曼树/编码

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;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值