求哈夫曼树最小带权路径长度和代码

来源:互联网 发布:黑客帝国矩阵革命 bt 编辑:程序博客网 时间:2024/05/16 04:59
/*样例输入51 2 2 5 9样例输出37输入可多次*/#include<stdio.h>#include<queue>using namespace std;priority_queue<int,vector<int>,greater<int> > Q;int main(){    int n;    int value;    while(scanf("%d",&n)!=EOF){            int ans = 0;        while(Q.empty()==false) Q.pop();        for(int i=0;i<n;i++){            scanf("%d",&value);            Q.push(value);        }        while(Q.size()>1){            int a = Q.top();            Q.pop();            int b = Q.top();            Q.pop();            ans+=a+b;            Q.push(a+b);        }        printf("%d\n",ans);    }    return 0;}