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

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

#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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44142774/article/details/115001606