码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-08 22:03:42      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:等于   http   统计   了解   mil   pac   mic   begin   ack   

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

 

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

标签:等于   http   统计   了解   mil   pac   mic   begin   ack   

原文地址:https://www.cnblogs.com/czc1999/p/10356630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!