九度oj 题目1172:哈夫曼树(优先队列实现最小堆)

链接

http://ac.jobdu.com/problem.php?pid=1172


题目描述:

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

输入:

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

输出:

输出权值。

样例输入:
5  
1 2 2 5 9
样例输出:
37
分析

使用最小堆,每次弹出权值两个最小的节点求权值然后将两者之和压入队列。

优先队列的函数

empty() 如果队列为空返回真

pop() 删除对顶元素

push() 加入一个元素

size() 返回优先队列中拥有的元素个数

top() 返回优先队列对顶元素


默认的是大根堆

priority_queue<int>q1;

定义int类型的小根堆

priority_queue<int,vector<int>,greater<int> >q;



ac代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;


int main()
{
    priority_queue<int,vector<int>,greater<int> >q;
    int T;
    while(cin>>T)
    {
        int weight1,weight2;
        long long result=0;
        int temp;
        for(int i=0; i<T; i++)
        {
            scanf("%d",&temp);
            q.push(temp);
        }
        while(!q.empty())
        {
            weight1 = q.top();
            result += weight1;
            q.pop();
            if(!q.empty())
            {
                weight2 = q.top();
                result += weight2;
                q.pop();
                q.push(weight1+weight2);
            }
            else
                result -= weight1;
        }
        printf("%d\n",result);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值