hdu2527 Safe Or Unsafe(哈夫曼树水)

每加一次相当于多一位编码。

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;

const int N = 50;
const int INF = 1000000;

struct node
{
    int w;
    friend bool operator < (const node &a, const node &b)
    {
        return a.w > b.w;
    }
};

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[5000];
    int a[30];
    int ans, C, num;
    scanf("%d", &C);
    while(C --)
    {
        cin >> num;
        scanf("%s", s);
        ans = 0;
        int len = strlen(s);
        memset(a, 0, sizeof(a));
        for(int i = 0; i < len; i ++)
            a[s[i] - 'a' + 1] ++;
        priority_queue <node> q;
        for(int i = 0; i < 27; i ++)
        {
            node tmp;
            tmp.w = a[i];
            if(tmp.w) q.push(tmp);
        }
        if(q.size() == 1) ans = len;//只有一种字符,每个字符一个字节,共len个
        else
        {
            while(q.size() > 1)
            {
                node tmp2, tmp3, tmp0;
                tmp2 = q.top();
                q.pop();
                tmp3 = q.top();
                q.pop();
                tmp0.w = tmp2.w + tmp3.w;
                ans += tmp2.w + tmp3.w;
                q.push(tmp0);
            }
        }
        if(ans < num) 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、付费专栏及课程。

余额充值