随手练——HDU Safe Or Unsafe (小根堆解决哈夫曼问题)

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

哈夫曼树,学完就忘得差不多了,题目的意思都没看懂,有时间复习下,看了别人的才知道是怎么回事。

贪心的题目,当总代价(要求最少)是由子代价累加或累乘出来,就可以考虑用哈夫曼来贪心。

 

 题意: 就是给你一个字符串如:12 helloworld 统计出其中 d:1个,e:1个,h:1个,l:3个,o:2个,r:1个,w:1个,然后用一个数组保存起来a[7]={1,1,1,1,1,2,3};然后就是用哈夫曼树的思想求出新建的非叶子节点的权值之和:sum与12相比较如果sum小于等于12的话就输出yes否则输出no,此案例求出的sum = 27;所以输出no。

解题思路:

建立小根堆,每次拿出来两个,并调整,再把这两个的和插入进去,直到数组长度为0。

我觉得这样要比建树来的思路清晰很多,当然前提是了解堆。

#include <string>
#include <map>
#include <iostream>
using namespace std;

void heapify(int *a,int index ,int length) {    
    while (index * 2 + 1 < length) {
        int left = index * 2 + 1;
        if (left + 1 < length&&a[left + 1] < a[left])left++;
        if (a[index] < a[left])break;
        swap(a[index], a[left]);
        index = left;

    }
}

void heapinsert(int *a,int index) {
    while (a[index] < a[(index - 1) / 2]) {
        swap(a[index], a[(index - 1) / 2]);
        index = (index - 1) / 2;
    }
}

int main() {
    int N;
    map<char, int>m;
    cin >> N;
    while (N--) {
        string str;
        int safe, res = 0;
        cin >> safe;
        cin >> str;
        for (int i = 0; i < str.length(); i++) {
            if (!m[str[i]]) m[str[i]] = 1;
            else m[str[i]]++;
        }
        int *a=new int[m.size()];
        int length = 0;
        for (map<char, int>::iterator it = m.begin(); it != m.end(); it++) {
            a[length++] = it->second;
        }
        for (int i = length / 2 - 1; i >= 0; i--) {
            heapify(a,i,length);
        }
        while (length > 0) {
            int m1 = a[0];
            swap(a[0], a[length - 1]);
            heapify(a, 0, --length);
            int m2 = a[0];
            swap(a[0], a[length - 1]);
            heapify(a, 0, --length);
            res += m1 + m2;
            if (length == 0)break;
            a[length] = m1 + m2;
            heapinsert(a,length++);
        }
        if (res <= safe) {
            cout << "yes" << endl;
        }
        else {
            cout << "no" << endl;
        }
        m.clear();
    }
}

 

转载于:https://www.cnblogs.com/czc1999/p/10356630.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值