利用优先级队列生成 哈夫曼树

来源:互联网 发布:淘宝买二手手机可靠吗 编辑:程序博客网 时间:2024/06/06 07:11
#include<stdio.h>#include<iostream>#include<stack>#include<string.h>#include <queue>using namespace std;//哈夫曼树//第一行输入一个数n,表示叶节点的个数//需要用这些叶节点生成哈夫曼树,//根据哈夫曼树的概念,这些结点有权值,即weight,//题目需要输出所有节点的值与权值的乘积之和priority_queue<int, vector<int> , greater<int> > Q; //建立一个小顶堆int main(){    freopen("in.txt", "r", stdin);    //freopen("out.txt", "w", stdout);    int n;    while(scanf("%d", &n) != EOF){        while( !Q.empty()){            Q.pop();        }        for(int i = 0; i < n; i++){            int x;            scanf("%d", &x);            Q.push(x);        }        int ans = 0;        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;}

原创粉丝点击