Many times the Huffman tree is not used to actually construct a Huffman tree, but only to obtain the minimum weighted path length. In this case, the priority queue can meet the requirements.
#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;
}
Structured priority queue
#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;
}