题目
笔者使用来自于acwing-148. 合并果子这题来对哈夫曼树的构建及其使用做出声明
在一个果园里,达达已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。
达达决定把所有的果子合成一堆。
每一次合并,达达可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。
可以看出,所有的果子经过 n−1 次合并之后,就只剩下一堆了。
达达在合并果子时总共消耗的体力等于每次合并所耗体力之和。
因为还要花大力气把这些果子搬回家,所以达达在合并果子时要尽可能地节省体力。
假定每个果子重量都为 1,并且已知果子的种类数和每种果子的数目,你的任务是设计出合并的次序方案,使达达耗费的体力最少,并输出这个最小的体力耗费值。
例如有 33种果子,数目依次为 1,2,9。
可以先将 1、2堆合并,新堆数目为 3,耗费体力为 3。
接着,将新堆与原先的第三堆合并,又得到新的堆,数目为 12,耗费体力为 12。
所以达达总共耗费体力=3+12=15。
可以证明 15 为最小的体力耗费值。
输入格式
输入包括两行,第一行是一个整数 n,表示果子的种类数。
第二行包含 n 个整数,用空格分隔,第 i 个整数 ai 是第 i 种果子的数目。
输出格式
输出包括一行,这一行只包含一个整数,也就是最小的体力耗费值。
输入数据保证这个值小于 231。
数据范围
1≤n≤10000
1≤ai≤20000
输入样例:
输出样例:
笔者解析
本题实际上是哈夫曼树的应用题目,原理与哈夫曼树相似,即每次找两个最小堆合并成一堆,最终得到最小花费。最终的值的大小为个子叶*度(子叶的高度或者说子叶在的层数减一)

笔者代码
java版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import java.io.*; import java.util.PriorityQueue;
public class Main { public static void main(String[] args) throws IOException { PriorityQueue<Integer> queue = new PriorityQueue<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(reader.readLine()); String []s = reader.readLine().split(" "); for (int i = 0; i < n; i++) { queue.offer(Integer.parseInt(s[i])); }
int ans = 0,a,b; while (queue.size()>1){ a=queue.poll(); b=queue.poll(); ans =ans+a+b; queue.add(a+b); }
writer.write(ans+" "); writer.flush(); writer.close(); reader.close(); } }
|
闫式C++版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> #include <algorithm> #include <queue>
using namespace std;
int main() { int n; scanf("%d", &n);
priority_queue<int, vector<int>, greater<int>> heap; while (n -- ) { int x; scanf("%d", &x); heap.push(x); }
int res = 0; while (heap.size() > 1) { int a = heap.top(); heap.pop(); int b = heap.top(); heap.pop(); res += a + b; heap.push(a + b); }
printf("%d\n", res); return 0; }
作者:yxc 链接:https: 来源:AcWing
|