题目描述:
Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.
FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.
Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.
Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.
输入:Line 1: One integer N, the number of planks
Lines 2..N+1: Each line contains a single integer describing the length of a needed plank
输出:Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts
解题思路:
属于二叉树叶子结点的最小带权路径问题,是哈夫曼树和哈夫曼编码的变种问题。题目中只需要计算权值,不需要编码,没必要构建哈夫曼树,只需要应用哈夫曼树的一个重要公式:每个叶子的带权路径之和 = 新生成结点的权值和。
还需要考虑边界情况,若农民大爷只需要1块模板,也就是只有一个结点,这也就没法构建哈夫曼树,也没有生成的新结点,需要单独处理。
解题步骤:
1、首先定义一个优先队列,按照升序排序,方便取权值最小的元素;
2、将输入的n个数据作为叶子结点的权值入队;
3、定义一个总和变量,用于存储带权路径和;如果输入的只有一个元素,总和就是这个元素,之结打印退出即可。
4、每次在队中取走最小权值的两个结点,两结点的权值之和作为新生成结点再入队,只要有新生成结点,都要把权值累加到总和变量中;直到队列中的元素少于两个,不能再合并为止。输出总和。
代码实现:
#include <iostream>
using namespace std;
#include <queue>
priority_queue<int, vector<int>, greater<int> > q;
int main()
{
int n;
cin >> n;
int temp = 0;
int total = 0, sum = 0;
for (int i = 0; i < n; i++)
{
cin >> temp;
q.push(temp);
}
if (n == 1)
{
total += q.top();
cout << total << endl;
return 0;
}
while (q.size() > 1)
{
sum = 0;
sum += q.top();
q.pop();
sum += q.top();
q.pop();
q.push(sum);
total += sum;
}
cout << total << endl;
return 0;
}