0
点赞
收藏
分享

微信扫一扫

【2016-3】字符串的哈夫曼编码长度

RIOChing 2022-07-14 阅读 48


1.题目

给定一个字符串(长度不超过100),求哈夫曼编码的最短长度

样例输入:
输入1:
abbcccdddd
输出1:
19

输入2:
we will we will r u
输出2:
50

2.思路

好像是第三次做这类似的题了。。用哈夫曼树统计带权路径长度WPL。
和​【哈夫曼树】合并果子(priority_queue)​类似。
只不过这题一开始需要利用map进行统计每个字符的个数,再利用​​​priority_queue​​模拟堆排序,每次将小顶堆的前两个最小值进行累加后,将累加的值temp存入队列中,依次累加temp即为所求。

3.代码

#include<iostream>
#include<queue>
#include<functional>
#include<string>
#include<map>
using namespace std;
priority_queue<int,vector<int>,greater<int>>q;
int main(){
string str;
getline(cin,str);
map<char,int>mp;
for(int i=0;i<str.size();i++){
mp[str[i]]++;
}
for(auto it=mp.begin();it!=mp.end();it++){
q.push(it->second);
}
int sum=0;
while(q.size()>1){//当至少有2个时
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int temp=a+b;
q.push(temp);
sum+=temp;
}
cout<<sum<<endl;
return 0;
}


举报

相关推荐

0 条评论