1. 程式人生 > >隨手練——HDU Safe Or Unsafe (小根堆解決哈夫曼問題)

隨手練——HDU Safe Or Unsafe (小根堆解決哈夫曼問題)

dex show () style 輸出 pre hello nbsp cin

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 (小根堆解決哈夫曼問題)