贪心: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;
}
相关推荐
Jerry2 小时前
LeetCode 459. 重复的子字符串
算法
哥不想学算法4 小时前
【C++】字符串字面量拼接
开发语言·c++
海石4 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石4 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
Jerry6 小时前
LeetCode 151. 反转字符串中的单词
算法
gugucoding7 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL8 小时前
我的数据结构3——链表(link list)
数据结构·链表
a1117769 小时前
LM 算法迭代过程动画演示(SLAM)
算法
头茬韭菜9 小时前
Context 的生死抉择:四层压缩、截断算法与 Session Memory
算法·ai
Jerry9 小时前
LeetCode 541. 反转字符串 II
算法