ZOJ-1117

8 篇文章 0 订阅
3 篇文章 0 订阅

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值