Huffman编码树构造,参考算法导论上的方法,用优先队列的话不难搞,但是由于对C++ STL完全不熟,查了N久API再加上参考大神代码才断断续续地写完,总算对priority_queue用法有了一定了解,下次应该不会这么坑了。。注意本题输入有AAAAAAAAAAAAAA这种串,要特殊处理下,否则WA
#include<cstdio>
#include<queue>
#include<string>
#include<iostream>
#include<map>
#include<vector>
using namespace std;
namespace
{
int total;
map<char, int> mp;
struct Node
{
char c;
int count;
Node *left;
Node *right;
};
struct cmp
{
bool operator()(Node* n1, Node* n2)
{
return n1->count > n2->count;
}
};
void dfs(Node *node, int depth)
{
if (node->c)
total += mp[node->c] * depth;
if (node->left)
dfs(node->left, depth + 1);
if (node->right)
dfs(node->right, depth + 1);
}
void destory(Node *node)
{
if (node->left)
destory(node->left);
if (node->right)
destory(node->right);
delete node;
}
}
int main()
{
string s;
while (cin >> s, s != "END")
{
mp.clear();
for (size_t i = 0; i < s.size(); i++)
if (mp.find(s[i]) == mp.end())
mp[s[i]] = 1;
else
mp[s[i]]++;
priority_queue<Node*, vector<Node*>, cmp> queue;
for (map<char, int>::iterator it = mp.begin(); it != mp.end(); it++)
{
Node *node = new Node();
node->c = it->first;
node->count = it->second;
queue.push(node);
}
if (queue.size() == 1)
{
Node *node = new Node();
queue.push(node);
}
while (queue.size() > 1)
{
Node *left = queue.top();
queue.pop();
Node *right = queue.top();
queue.pop();
Node *now = new Node();
now->count = left->count + right->count;
now->left = left;
now->right = right;
queue.push(now);
}
total = 0;
dfs(queue.top(), 0);
destory(queue.top());
queue.pop();
printf("%d %d %.1lf\n", s.size() * 8, total, s.size() * 8.0 / total);
}
return 0;
}