优先队列的使用

来源:互联网 发布:mac 翻墙付费软件 编辑:程序博客网 时间:2024/06/04 01:16


运用哈弗曼贪心选择

选择两个最小的值合并,加入优先队列


#include<queue>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define LL long longpriority_queue<LL,vector<LL>,greater<LL> >q;int main(){    LL n,T,t;    //freopen("in.txt","r",stdin);    scanf("%lld",&T);    while(T--)    {        while(!q.empty())            q.pop();        scanf("%lld",&n);        for(int i=0;i<n;i++){            scanf("%lld",&t);            q.push(t);        }        LL ans=0,a,b;        while(q.size()>1)        {            a=q.top();q.pop();            b=q.top();q.pop();            ans+=a+b;            q.push(a+b);        }        printf("%lld\n",ans);    }    return 0;}