Multivariate Huffman coding problem

Problem description: There are n piles of stones placed around a playground. Now the stones are to be combined into one pile in an orderly manner. It is stipulated that each time at least 2 piles and at most k piles of stones are selected and combined into a new pile, and the cost of the combination is the number of the new pile of stones. Calculate the maximum total cost and minimum total cost of combining n piles of stones into one pile.


Algorithm design: For a given n piles of stones, calculate the maximum total cost and the minimum total cost combined into one pile.
Data input: There are 2 positive integers n and k in the first line of the file, which means that there are n piles of stones, and at least 2 piles and at most k piles of stones are selected each time. There are n numbers in the second row, which represent the number of stones in each pile.
Input example:
7 3
45 13 12 16 9 5 22
Output example:
593 199 

Idea: Use the largest pile to choose the two largest piles at a time, and the total is the maximum cost. Use the smallest heap to select the smallest heap of k every time, and the total is the smallest. (do not know why)

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main()
{
	int n, k;
	while (cin >> n >> k)
	{
		vector<int>v;
		v.push_back(0);
		priority_queue<int, vector<int>, less<int>>p;
		priority_queue<int, vector<int>, greater<int>>q;
		for (int i = 1; i <=n; i++)
		{
			int num;
			cin >> num;
			v.push_back(num);
			p.push(num);
			q.push(num);
		}
		
		int max_sum=0, top;
		while (p.size() > 1)
		{
			top = p.top();
			p.pop();
			top+=p.top();
			p.pop();
			max_sum += top;
			p.push(top);
		
		}
		int min_sum = 0;
		while (q.size() > k)
		{
			top = 0;
			for (int i = 0; i < k; i++)
			{
				top += q.top();
				q.pop();

			}
			q.push(top);
			min_sum += top;

		}
		while (q.size())
		{
			top = q.top();
			min_sum += top;
			q.pop();
		}
		cout << "maxs_sum: " << max_sum << "min_sum: " << min_sum << endl;
	}

	return 0;
}
/*
7 3
45 13 12 16 9 5 22

*/

 

Guess you like

Origin blog.csdn.net/weixin_40823740/article/details/109370227