贪心: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;
}
相关推荐
apcipot_rain8 小时前
C++转Java日记(04)
java·开发语言·c++
NEFU_Jyj8 小时前
牛客周赛R168
算法
WL学习笔记10 小时前
vector模拟实现
c++
蜗牛一步步往上爬12 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
likexuec15 小时前
数据结构(2)
数据结构
Navigator_Z16 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack16 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH17 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶17 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划