hdu2527 Huffman Coding

本文提供了一种解决HDU 2527问题的算法实现方案,利用优先队列来构建赫夫曼树,并通过深度优先搜索计算最优解,最终判断是否能在给定限制条件下完成字符串编码。
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char s[100005];
int t;
struct dian
{
    friend bool operator < (dian n1,dian n2)
     {
         return (n1.x>n2.x);
     }
     int node,l,r,x;
};
dian n[105],n1,n2;
int dfs(int no,int depth)
{
    if (n[no].l==-1) return(depth*n[no].x);
    else return(dfs(n[no].l,depth+1)+dfs(n[no].r,depth+1));
}
int main()
{
    int T,m,len,i,tt,sum,hash[105];
    priority_queue<dian>q;
    while (~scanf("%d",&T))
    while (T--)
    {
        scanf("%d",&m);
        getchar();
        memset(hash,0,sizeof(hash));
        scanf("%s",s); len=strlen(s);
        for (i=0;i<len;i++) hash[s[i]-'a']++;
        t=0;
        while (!q.empty()) q.pop();
        for (i=0;i<26;i++)
         if (hash[i]!=0)
         {
             t++;
             n[t].x=hash[i];
             n[t].node=t;
             n[t].l=n[t].r=-1;
             q.push(n[t]);
         }
        tt=t;
        while (q.size()!=1)
        {
            n1=q.top(); q.pop();
            n2=q.top(); q.pop();
            tt++;
            n[tt].x=n1.x+n2.x;
            n[tt].node=tt;
            n[tt].l=n1.node; n[tt].r=n2.node;
            q.push(n[tt]);
        }
        sum=dfs(tt,0);
//      for (i=1;i<=tt;i++) printf("%d %d %d %d\n",n[i].node,n[i].x,n[i].l,n[i].r);
//      printf("%d\n",sum);
        if ((sum<=m&&t!=1)||(t==1&&n[1].x<=m)) printf("yes\n");
        else printf("no\n");
    }
}

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

转载于:https://www.cnblogs.com/xiao-xin/articles/3848645.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值