优先队列实现哈弗曼最小权值

来源:互联网 发布:php开发网站兼容问题 编辑:程序博客网 时间:2024/06/05 21:39
建立哈弗曼树要求我们每次都选频率权值最小的点构成节点,即权值小的点在树的深处,权值大的点在树的浅处,根据节点选择的特点,我们可以把节点的值放在优先队列中,包括新形成的节点。

我们先定义优先队列的优先级别。

1 struct cmp2 {3    bool operator()(const int &a,const int &b)4    {5        return a>b;6    }7 };//最小值优先出队

然后就是实现的整个程序。

#include<stdio.h>#include<string.h>#include<algorithm>#include<iostream>#include<queue>#define maxn 50050using namespace std;struct cmp{   bool operator()(const int &a,const int &b)   {       return a>b;   }};int main(){   int n;   while(scanf("%d",&n)!=EOF)   {       int x;       priority_queue<int,vector<int>,cmp>q;       for(int i=0;i<n;i++)       {           scanf("%d",&x);           q.push(x);       }       __int64 sum=0;       while(q.size()!=1)       {           int a=q.top();           q.pop();           int b=q.top();           q.pop();           sum+=a+b;           q.push(a+b);       }       printf("%I64d\n",sum);   }   return 0;}

练习题链接
http://www.51nod.com/onlineJudge/questionCode.html#problemId=1117&noticeId=19046

 

0 0
原创粉丝点击