字符串“liulishuo”,我们需要对该字符串每个字符编码,使得编码后的字符串总长度最小。
我们可以通过哈夫曼树来对字符编码,累积树中非叶子节点的和即为所求总长度。
总长度也等于词频1字符长度1+词频2字符长度2+…
/*
liulishuo
23
对字符串编码,使得编码后的总长度最短;
哈夫曼编码,总长度=字符长度1*频数1+字符长度2*频数2
利用最小堆找最小元素
*/
int MinLength(string str)
{
// 统计词频
unordered_map<char, int> m;
for (char ch : str)
{
m[ch]++;
}
priority_queue<int,vector<int>,greater<int>> q;
unordered_map<char, int>::iterator it = m.begin();
int count = 0;
//通过词频构建优先队列
for (it; it != m.end(); it++)
{
q.push(it->second);
count++;
}
int res = 0;
//cout << count << endl;
// 总长度也可以通过累积哈夫曼树非叶子节点的和得到,其中非叶子节点数=字符数-1
while (count-->1)
{
int q1 = q.top();
q.pop();
int q2 = q.top();
q.pop();
q.push(q1 + q2);
//cout << q1 + q2 << endl;
res += q1 + q2;
}
return res;
}
参考:https://blog.youkuaiyun.com/u011391629/article/details/72971601