优先队列与哈夫曼树的求解

很多时候用到哈夫曼树不会去真正的构建一棵哈夫曼树,而仅仅是为了求得那个最小带权路径长度,这时用优先队列即可满足要求。

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    priority_queue<ll,vector<ll>,greater<ll> > p;
    int i,n;
    ll data,ans = 0;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>data;
        p.push(data);
    }
    while(p.size()>1)
    {
        ll a = p.top();
        p.pop();
        ll b = p.top();
        p.pop();
        p.push(a+b);
        ans+=(a+b);
    }
    p.pop();
    cout<<ans;
    return 0;
}

结构体的优先队列

#include<bits/stdc++.h>
using namespace std;
struct Node{
    int x,y;
    Node (int _x,int _y)
    {
        this->x = _x;
        this->y = _y;
    }
//    friend bool operator<(Node n1,Node n2)
//    {
//        return n1.x>n2.x;
//    }
};
class compare{
public:
    bool operator()(Node n1,Node n2)
    {
        return n1.x<n2.x;
    }
};
int main()
{
    //友元重载
    //priority_queue<Node> p;
    priority_queue<Node,vector<Node>,compare> p;
    p.push(Node(1,2));
    p.push(Node(2,1));
    p.push(Node(4,1));
    cout<<p.top().x<<endl;
    p.pop();
    cout<<p.top().x<<endl;
    p.pop();
    cout<<p.top().x<<endl;
    p.pop();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值