贪心:Huffman树

合并果子:

该题与石子合并的区别:石子合并是两两相邻才能合并,这题是任意两点合并

该题的思路:每次合并最小的两个点

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

int main()
{
    int n;
    scanf("%d", &n);

    priority_queue<int, vector<int>, greater<int>> heap;//小根堆,所以堆头是最小值
    while (n -- )
    {
        int x;
        scanf("%d", &x);
        heap.push(x);
    }

    int res = 0;//答案
    while (heap.size() > 1)//只要超过两个数,就两个合并。因为是小根堆,每次合并的都是最小的两个
    {
        int a = heap.top(); heap.pop();
        int b = heap.top(); heap.pop();
        res += a + b;
        heap.push(a + b);
    }

    printf("%d\n", res);
    return 0;
}
相关推荐
yong15858553438 小时前
2. Linux C++ muduo 库学习——原子变量操作头文件
linux·c++·学习
夏乌_Wx8 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode
小小8程序员9 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
立志成为大牛的小牛9 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
a努力。9 小时前
Redis Java 开发系列#2 数据结构
java·数据结构·redis
老王熬夜敲代码9 小时前
C++中的atomic
开发语言·c++·笔记·面试
沿着路走到底9 小时前
将数组倒序,不能采用reverse,算法复杂度最低
算法
IDIOT___IDIOT9 小时前
KNN and K-means 监督与非监督学习
学习·算法·kmeans
Hcoco_me10 小时前
大模型面试题18:t-SNE算法详解及入门实操
算法