蓝桥题目:B-28、Huffman树

蓝桥题目:B-28、Huffman树_第1张图片
用list方法,sort排序,删除最小两个,添加他们和进去,很简单可以解决

#include 
#include 

using namespace std;

typedef list<int> LISTINT;

int main(){
	LISTINT list;
	LISTINT::iterator ir;
	
	int n;
	cin >> n;
	int temp;
	for(int i = 0; i < n; ++i){
		cin >> temp;
		list.push_back(temp);
	}
	
	int cost = 0;
	do{
		list.sort();
		ir = list.begin();
		temp = *ir + *(++ir);
		cost += temp;
		list.erase(list.begin());
		list.erase(list.begin());
		list.push_back(temp);
	}while(list.size() != 1);
	
	cout << cost;
	return 0;
} 

网上摘的别人的用priority_queue优先队列加vector的
应该更符合实际应用
https://blog.csdn.net/cprimesplus/article/details/89930008

#include
#include
#include
#include
#include
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{//优先队列中按weight属性比较的方法
	bool operator()(Huffman *&a, Huffman *&b){return a->weight >= b->weight;}
};
typedef priority_queue<Huffman*,vector<Huffman*>,cmp> Prior;//优先队列按cmp排序
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]);//加入队列,会自动按cmp排序
	}
	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节点加入链表
		temp->weight = t1->weight + t2->weight;
		cnt += temp->weight;
		p.push(temp);//temp加入队列
	}
	return 0;
}
int main()
{
	CreateHuffTree();
	return 0;
}

你可能感兴趣的:(Lanqiao)