数据结构--哈夫曼树

构造一棵哈夫曼树并计算最短路径长度


#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

//构造一棵哈夫曼树,
//并求其带权路径长度
void HafumanTree(){
    //构建封装小根堆的优先级队列
    priority_queue<int,vector<int>,greater<int>> myPriorityQueue;
    //构建封装大根堆的优先级队列
    priority_queue<int> hafuman;
    //添加哈夫曼树的叶子节点
    int n;
    scanf("%d",&n);
    for(int i = 0;i < n;i++){
        int x;
        scanf("%d",&x);
        myPriorityQueue.push(x);
        hafuman.push(x);
    }
    //遍历优先级队列,并求得其最短路径长度
    int paths = 0;
    while(myPriorityQueue.size() > 1){
        int x = myPriorityQueue.top();
        myPriorityQueue.pop();
        int y = myPriorityQueue.top();
        myPriorityQueue.pop();
        paths += x+y;
        myPriorityQueue.push(x+y);
        hafuman.push(x+y);
    }
    //遍历哈夫曼树
    while(!hafuman.empty()){
        printf("%d ",hafuman.top());
        hafuman.pop();
    }
    printf("\n");
    printf("%d\n",paths);

}

int main()
{
   HafumanTree();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值