哈夫曼树

7-11 哈夫曼树 (25 分)

哈夫曼树,第一行输入一个数n,表示叶结点的个数。

需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出哈夫曼树的带权路径长度(WPL)。

输入格式:
第一行输入一个数n,第二行输入n个叶结点(叶结点权值不超过1000,2<=n<=1000)。

输出格式:
在一行中输出WPL值。

输入样例:

5
1 2 2 5 9

输出样例:

37

上代码:

#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int Data;
    friend bool operator<(struct Node nod1,struct Node nod2){
        return nod1.Data>nod2.Data;
    }
};

int main()
{
    priority_queue<Node> que;
    int N;
    cin>>N;
    struct Node arr[N];
    int weight;
    for(int i=0; i<N; i++)
    {
        cin>>weight;
        arr[i].Data=weight;
        que.push(arr[i]);
    }
    int sum=0;
    for(int i=0;i<N-1;i++){
        int temp1=que.top().Data;
        que.pop();
        int temp2=que.top().Data;
        que.pop();
        int newNode=0;
        newNode=temp1+temp2;
        Node key;key.Data=newNode;
        sum=sum+newNode;
        que.push(key);
        if(que.size()==1){
            cout<<sum<<endl;
            break;
        }
    }
    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值