【 OJ 】 HDOJ1053 18年12月20日16:59 [ 47 ]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QingCoffe/article/details/85127524

这题一开始做出来没被AC很郁闷,后来人家提到1个字符的时候我才发现,我定义的函数初始Power是0,一个字符的时候会除0出现这种 Inf 错误

思路就是模拟下哈夫曼编码树即可拿到每一个编码的个数求出总个数

已经被AC

# include<iostream>
#include<iomanip>
# include<string>
# include<map>
# include<queue>
using namespace std;
struct node {
	char a;
	int pow;
	node*lc;
	node*rc;
};
struct cmp {
	bool operator()(node&a, node&b) {
		return a.pow > b.pow;
	}
};
priority_queue<node,vector<node>,cmp > pq;
map<char, int>Map;
void Travel(node*R, int Power) {
	if (!R)return;
	Travel(R->lc, Power + 1);
	Travel(R->rc, Power + 1);
	map<char, int>::iterator it;
	if (!R->lc && !R->rc) {
		it = Map.find(R->a);
		if (it != Map.end())it->second = Power?Power:1;//开始没注意1个字符Inf问题
	}
}
int main(void) {
	string s;
	cin >> s;
	while (strcmp(s.c_str(),"END")) {
		map<char, int>::iterator it;
		for (int i = 0; i < s.length(); i++) {
			it = Map.find(s[i]);
			if (it != Map.end())
				(it->second)++;
			else
				Map.insert(make_pair(s[i], 1));
		}//插入不重复的map中统计各个符号个数(权值)
		for (it=Map.begin(); it != Map.end(); it++) {
			node temp;
			temp.a = it->first; temp.pow = it->second; temp.lc = temp.rc = NULL;
			pq.push(temp);//进优先队列中去
		}//拿到每个字母的权值进优先队列
		node *Root=NULL;
		while (!pq.empty()) {
			node *LC; node*RC; node* R; LC = RC = R = NULL;
			LC = (node*)malloc(sizeof(node)); if (!LC)exit(-1);
			RC = (node*)malloc(sizeof(node)); if (!RC)exit(-1);
			R = (node*)malloc(sizeof(node)); if (!R)exit(-1);
			*LC = pq.top(); pq.pop();
			if (pq.empty()) { Root = LC; free(R); free(RC); break; }
			*RC = pq.top(); pq.pop();
			R->lc = LC; R->rc = RC; R->a = ' '; R->pow = LC->pow + RC->pow;
			pq.push(*R);
		}//构造哈夫曼树
		Travel(Root,0);//拿到哈夫曼编码个数
		int res1, res2; double res3;	res1 = res2 = 0; res3 = 0.0;
		for (int i = 0; i < s.length(); i++) {
			it = Map.find(s[i]);
			if (it != Map.end()) {//一定可以找到,如果找不到前面出了问题
				res2 += it->second;
			}
		}
		res1 = 8 * s.length(); res3 = res1 / (double)res2;
		cout << res1 << " " << res2 << " ";
		cout.setf(ios::fixed);
		cout << setprecision(1) << res3 << endl;
		//---------------------------------初始化Map和pq
		it = Map.begin();
		map<char, int>::iterator itt;
		itt = it;
		while (it != Map.end()) {
			it++; Map.erase(itt); itt = it;
		}
		while (!pq.empty())pq.pop();
		//---------------------------------
		cin >> s;
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/QingCoffe/article/details/85127524