字元編碼(哈夫曼編碼)
阿新 • • 發佈:2019-02-20
Question
請設計一個演算法,給一個字串進行二進位制編碼,使得編碼後字串的長度最短。
Algorithm
哈夫曼編碼,權為各個字元出現的頻率,再借助小根堆計算。
result=詞頻1*深度1+詞頻2*深度2…
詞頻可以藉助雜湊表統計,而深度可以通過小根堆來實現
比如:
MT-TECH-TEAM
雜湊表統計完字元出現的次數後,為1,1,1,2,2,2,3
找出權最小的2個(1,1),生成新的結點2(重複此步驟)
1,2,2,2,2,3(res=2)
2,2,2,3,3(res=2+3=5)
2,3,3,4(res=5+4=9)
3,4,5(res=9+5=14)
5,7(res=14+7=21)
12(res=21+12=33)
這樣做的依據是可以計算每個權在樹中的深度。
Code
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<queue>
#include<map>
#include<functional>
using namespace std;
int main(){
string str;
while (cin >> str){
map<char, int > hash;
for (int i = 0; i<str.size(); i++){
hash[str[i]]++;
}
map<char, int>::iterator it = hash.begin();
priority_queue<int, vector<int>, greater<int>> q;
int cnt = 0;
for (; it != hash.end(); it++){
q.push(it->second);
cnt++;
}
int x1, x2;
int res = 0;
while (--cnt > 0){
x1 = q.top(); q.pop();
x2 = q.top(); q.pop();
res += x1 + x2;
q.push(x1 + x2);
}
cout << res << endl;
}
return 0;
}