HDU 2527 Safe Or Unsafe 哈夫曼树

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=2527


明天蓝桥杯比赛,看了一下以前做的题目,发现好多都要看下以前写的才能AC,哎。。。。

一道基本的哈夫曼树问题,直接用优先队列模拟。


代码入下:

#include<iostream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;

typedef long long LL;
const int N=101000;

char s[N];
int a[27];

struct xh
{
    int t;
    friend bool operator<(xh aa,xh bb)
    {
        return aa.t>bb.t;
    }
}w;

int main()
{
    int i,j,len,T,sum,n;
    cin>>T;
    while(T--)
    {
        scanf("%d%s",&n,s);
        len=strlen(s);
        memset(a,0,sizeof(a));
        for(i=0;i<len;i++)
            a[s[i]-'a']++;
        priority_queue<xh> q;
        len=0;
        for(i=0;i<26;i++)
            if(a[i])
            {
                w.t=a[i];
                q.push(w);
                len++;
            }
        if(len==1)
        {
            sum=q.top().t;
        }
        else
        {
            int i=0;
            sum=0;
            while(i<len-1)
            {
                int x=q.top().t;
                q.pop();
                int y=q.top().t;
                q.pop();
                sum+=x+y;
                w.t=x+y;
                q.push(w);
                i++;
            }
        }
        if(sum<=n)
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值