Repair the pasture (the easy-to-understand Huffman tree (greedy thinking))

Repair ranch

The farmer wants to repair a section of the fence on the ranch. He measured the fence and found that N pieces of wood are needed. The length of each piece of wood is an integer Li units of length. So he bought a very long piece of wood that can be sawn into N pieces. The length is the sum of Li.
But the farmer does not have a saw himself, and the reward for using someone to saw the wood is proportional to the length of the wood. For the sake of simplicity, set the reward equal to the length of the sawn wood. For example, to saw a length of 20 wood into three segments with lengths 8, 7, and 5. The first time sawing the wood costs 20, and the wood is sawing 12 and 8; the second time sawing the wood costs 12, and the length is 12 Of wood sawn into 7 and 5, the total cost is 32. If the wood is sawed into 15 and 5 for the first time, the second sawing will cost 15 and the total cost will be 35 (more than 32).
Please write a program to help the farmer calculate the minimum cost of sawing wood into N pieces.

Input format:

The input first gives a positive integer N (≤10^4), which means that the wood is to be sawn into N pieces. The second line gives N positive integers (≤50), indicating the length of each piece of wood.

Output format:

Output an integer, the minimum cost of sawing wood into N pieces.

Input sample:

8
4 5 1 2 1 3 1 1

Sample output:

49

Title:

The idea is very simple. Divide a long piece of wood into n pieces of wood. When you want to cut the current wood, you need to pay a cutting fee. The cutting fee is equal to the length of the current wood. It ends when you get n pieces of small wood. (Long wood must be the sum of n pieces of small wood), and finally find the minimum cost.

Ideas:

Now the length (result) of n pieces of small wood is given, so if you want to know how to cut, you can only push back. Here are three pushback diagrams, Figure a, Figure b, Figure c

.Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

Code

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
//这里利用最小堆,即放入队列中的元素会自动从小到大排序。
//为什么要有这个呢 
//因为每次都需要找出最小的两个,即需要排序 
priority_queue<int,vector<int>,greater<int> > q;
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		int i,x,a,b,s,sum=0;
		while(!q.empty())
			q.pop();
		for(i=0;i<n;i++)
		{
			scanf("%d",&x);
			q.push(x);
		}
		while(q.size()>=2)
		{
			a=q.top();
			q.pop();
			b=q.top();
			q.pop();
			s=a+b;
			q.push(s);
			sum+=s;
		}
		printf("%d\n",sum);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Helinshan/article/details/111709442