蓝桥题目:B-28、Huffman树


用list方法,sort排序,删除最小两个,添加他们和进去,很简单可以解决

#include <iostream>
#include <list>

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<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{//优先队列中按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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值