优先队列实现哈夫曼树

//优先队列实现哈夫曼树
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
//法一
struct cmp  //最小值优先
{
 bool operator ()( int &a, int &b)
 {
  if(a!=b)
      return a>b;
 }
};
struct cmp  //最小值优先
{
 bool operator ()(const int &a,const int &b)
 {
  if(a!=b)
      return a>b;
 }
};
struct cmp  //最大值优先
{
 bool operator ()(const int &a,const int &b)
 {
  if(a!=b)
      return a<b;
 }
};
//法二
//由大到小
struct node
{
 int x;
 friend bool operator <(const node &a,const node &b)
 {
  if(a.x!=b.x)
      return a.x<b.x;
 }
 } ;
 //法三
struct node
{
 int x;
 bool operator <(const node &a)const
 {
  
      return x<a.x;
 }
 } ;
int main(void)
{
 int n;
 int a;
 cin>>n;
 priority_queue<int,vector<int>,cmp> pq;//法一
 //priority_queue<node> pq;//法二 三
 for(int i=0;i<n;i++)
 {
  cin>>a;
  pq.push(a);
 }
 int val=0;
 while(pq.size()>1)
 {
  int min1=pq.top();
  pq.pop();
  int min2=pq.top();
  pq.pop();
  min1+=min2;
  val+=min1;
  pq.push(min1);
 }
 cout<<val<<endl;
 return 0;
 }

猜你喜欢

转载自www.cnblogs.com/cxwpluto/p/12441141.html