Fortune left France 4 basis class7- title cut bullion problem

Fortune left France 4 basis class7- title cut bullion problem

1. Topic

A bullion cut in half, and takes a value the same as the length of the copper plate. For example, a length of 20 gold bars, cut into two halves regardless of how much length, must spend 20 copper. A group of people who want to divide the entire block of gold bullion, how to divide the province most copper?
For example, given the array {10, 20}, representing a total of three, the entire length of bars 10 + 20 + 30 = 60. Bullion to be divided into three parts 10,20,30. If the length of the first bars 10 and 60 into 50, 60 takes the bars 50 and then into a length of 20 and 30, a total cost spent 50 110 copper. If, however, the length of the first bars 30 and 60 into 30, 60 then take a length of bars 30 and 20 into 10, 30 spent a total of 90 spent copper.
An input array, divided returns minimum cost.

2. Analysis

Standard Huffman coding problem: the cost of child nodes merged together and
greedy strategy
Here Insert Picture Description
all non-leaf nodes and 30 + 60 = 90 is the solution to this question. Generates the lowest cost approach:
① all the numbers added to a small heap root
② out of every two numbers, then put it back merge
③ until only a number, that number is the price

3. The complete code

#include<queue> 
#include<iostream>
using namespace std;
int main()
{

	int a[] = {10,20,30};
	vector<int> v(a,a + 3);
	int sum = 0;
	priority_queue<int,vector<int>,greater<int> > pq;
	for(auto c : v)
	{
		pq.push(c);
	}
	while(pq.size() > 1)
	{
		int num1 = pq.top();
		pq.pop();
		int num2 = pq.top();
		pq.pop();
		int cur = num1 + num2;
		sum += cur;
		pq.push(cur);
	}
	cout<<sum<<endl;
	return 0;
}
Published 51 original articles · won praise 1 · views 1365

Guess you like

Origin blog.csdn.net/shi_xiao_xuan/article/details/104818389