蓝桥杯之Huffman树

版权声明:本文为博主原创文章,转载请附明出处^_^ https://blog.csdn.net/cprimesplus/article/details/89930008

题目描述
在这里插入图片描述

解析
  把这道题作为哈夫曼算法的练习题,没什么难度,只是输出每次构造的子树的结点值,使用cnt在每次合并操作时做记录即可。

代码

#include<iostream>
#include<queue>
#include<vector>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int MAX_SIZE = 1024;
typedef struct node{
	int weight;
	struct node *left, *right;
	
	node(int weight){this->weight = weight;}
}Huffman;
struct cmp{
	bool operator()(Huffman *&a, Huffman *&b){return a->weight >= b->weight;}
};
typedef priority_queue<Huffman*,vector<Huffman*>,cmp> Prior;
void Alloc(Huffman *&a, int weight)
{
	a = (Huffman *)malloc(sizeof(Huffman));
	a->weight = weight;
	a->left = NULL;
	a->right = NULL;
}
int CreateHuffTree()
{
	Prior p;
	int n, cnt = 0, t;
	Huffman *a[MAX_SIZE];
	cin>>n;
	for(int i = 0;i < n;i++){
		 cin>>t;
		 Alloc(a[i], t);
		 p.push(a[i]);
	}
	while(!p.empty())
	{
		Huffman *t1 = p.top();p.pop();
		if(p.empty()){
			cout<<cnt<<endl;
			return 0;
		}
		Huffman *t2 = p.top();p.pop();
		Huffman *temp;
		Alloc(temp, 0);
		temp->left = t1;
		temp->right = t2;
		temp->weight = t1->weight + t2->weight;
		cnt += temp->weight;
		p.push(temp);
	}
	return 0;
}
int main()
{
	CreateHuffTree();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cprimesplus/article/details/89930008