[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 @   wKingYu  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
欢迎阅读『[AcWing 148] 合并果子』
点击右上角即可分享
微信分享提示