POJ3253 Huffman Tree

来源:互联网 发布:手机健身运动软件 编辑:程序博客网 时间:2024/05/21 00:53

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

Sample Input

3858

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