优先队列priority_queue知识点总结:
- 只能用top()访问元素,常用函数有top/push/pop/empty/size
- 优先级设置
思路:
- 字符出现的频率则为其权值
- 哈夫曼树的编码长度等于各个叶节点权值与路径长度乘积之和,同时这个值等于非叶节点之和
#include<iostream> #include<functional> //支持greater #include<string> #include<queue> #include<map> using namespace std; map<char, int> mp; //字符到整型的映射map<char,int>,字符串到整型的映射 map<string,int> priority_queue<int,vector<int>,greater<int> > q; int main() { string s; getline(cin, s); //类似char数组的gets,吸收一行,包括空格,用cin>>str,不能吸收空格 for (int i = 0; i < s.length(); i++) { mp[s[i]]++; } int ans = 0; map<char, int>::iterator it; for (it = mp.begin(); it != mp.end(); it++) q.push(it->second); while (q.size()!=1) { //不是!q.empty() int a = q.top(); q.pop(); int b = q.top(); q.pop(); int x = a + b; ans += x; q.push(x); } cout << ans; system("pause"); return 0; }