POJ3253 Huffman Tree

2017年3月29日 | ljfcnyali
题目大意
FJ需要修补牧场的围栏,他需要 N 块长度为 Li 的木头(N planks of woods)。开始时,FJ只有一块无限长的木板,因此他需要把无限长的木板锯成 N 块长度。

Sample Input

3
8
5
8

Sample Output

34

题目分析
直接一个哈夫曼水过好不好,

Huffman Tree
给定 N planks of woods,
1.在 N planks 中每次找出两块长度最短的木板,然后把它们合并,加入到集合A中,
2.在集合中找出两块长度最短的木板,合并加入到集合A中,重复过程,直到集合A中只剩下一个元素
显然,通过每次选取两块长度最短的木板,合并,最终必定可以合并出长度为 Sum(Li)的木板,并且可以保证总的耗费最少.

陷阱分析
要开Long Long!

AC代码

/*************************************************************************
    > File Name: POJ3253.cpp
    > Author: ljf-cnyali
    > Mail: ljfcnyali@gmail.com 
    > Created Time: 2017/3/29 19:53:03
 ************************************************************************/

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>

using namespace std;

#define REP(i, a, b) for(long long i = (a), _end_ = (b);i <= _end_; ++ i)
#define mem(a) memset((a), 0, sizeof(a))
#define str(a) strlen(a)

const long long maxn = 10000;

long long n, x, a, b;

long long ans;

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    while(~scanf("%lld", &n)) {
        priority_queue<long long, vector<int>, greater<int> > Q;
        REP(i, 1, n) {
            scanf("%lld", &x);
            Q.push(x);
        }
        ans = 0;
        if(Q.size() == 1) {
            a = Q.top();
            ans += a;
            Q.pop();
        }
        while(Q.size() > 1) {
            a = Q.top();
            Q.pop();
            b = Q.top();
            Q.pop();
            x = a + b;
            ans += x;
            Q.push(x);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

本文转自:http://ljf-cnyali.cn/index.php/archives/119

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值