[AcWing 148] 合并果子

image
image


点击查看代码
#include<iostream>
#include<vector>
#include<queue>

using namespace std;

int n, res;
priority_queue<int,vector<int>,greater<int>> heap;

int main()
{
	cin >> n;
	for (int i = 0; i < n; i ++) {
		int x;
		cin >> x;
		heap.push(x);
	}
	while (heap.size() > 1) {
		int t1 = heap.top();
		heap.pop();
		int t2 = heap.top();
		heap.pop();
		res += t1 + t2;
		heap.push(t1 + t2);
	}
	cout << res << endl;
	return 0;
}

  1. 算法思路
    建立哈夫曼树:每次从集合中取出最小的两个元素进行合并,并把合并后的结果放入集合中,直到集合中只剩一个元素
  2. 利用小根堆来维护集合中的最小值
posted @ 2022-06-14 20:04  wKingYu  阅读(31)  评论(0)    收藏  举报