PS.学习priority_queue,请直接到文末点击链接。此篇是priority_queue解决哈夫曼树问题。

研究生考试机试:

哈夫曼树

题目描述:

哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。

输入:

输入有多组数据。

 每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。

输出:

输出权值。

样例输入:

1 2 2 5 9

样例输出: 37

-----------------------分割线-------------

九度oj上一个人的解法:

语言:C

#include<functional>
#include<stdio.h>
#include<queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> > Q;
int main() {//program 哈夫曼树
    int n, ans = 0;
    while (scanf("%d", &n) != EOF) {
        while (Q.empty() == false)Q.pop();
        for (int i = 0; i < n; i++) {
            int x;
            scanf("%d", &x);
            Q.push(x);
        }
        ans = 0;
        while (Q.size() > 1) {
            int a = Q.top();
            Q.pop();
            int b = Q.top();
            Q.pop();
            ans = ans + a + b;
            Q.push(a + b);
        }
        printf("%d\n", ans);
    }
    return 0;
}

以上代码用priority_queue解决了问题。

网上搜索priority_queue,看到一篇学习贴,链接http://www.cnblogs.com/flyoung2008/articles/2136485.html

从中受益。

 

posted on 2017-03-15 16:54  %^v^%  阅读(553)  评论(0编辑  收藏  举报