贪心: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;
}
相关推荐
HaiXCoder2 小时前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++
武子康3 小时前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer3 小时前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航
时间的拾荒人3 小时前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
老师我太想进步了20265 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
kyle~6 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
geats人山人海6 小时前
现代c++4.1
java·开发语言·c++
Pniubi7 小时前
贪心算法入门
算法·贪心算法
MobotStone7 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
复杂网络与机器学习8 小时前
Meta 重写 K-Means:25 轮压成 2 轮,GPU 快 45 倍
人工智能·算法·数据挖掘