数据结构——哈夫曼树

可参考priority_queue(优先队列)讲解_priority------queue-CSDN博客

例题148. 合并果子 - AcWing题库

用优先队列(堆-完全二叉树)来实现哈夫曼树,每次取小根堆队头两元素相加为一个,pop完再push进去,相当于模拟哈夫曼树的构造了。

代码如下:

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
#define fs first
#define sc second
#define endl '\n'
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;

void solve(){
    priority_queue<int,vector<int>,greater<int>> q;//小根堆
    
    int n;cin>>n;
    
    for(int i=0;i<n;i++)
    {
        int x;cin>>x;
        q.push(x);
    }
    
    int ans=0;
    
    while(q.size()>1)
    {
    	//取最小的两个元素
        int a=q.top();q.pop();
        int b=q.top();q.pop();
        ans+=(a+b);
        q.push(a+b);
    }
    
    cout<<ans<<endl;
}

int main(){
	
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);

    int t;
    t=1;

    while (t--)
    {
        solve();
    }
    
    return 0;
}
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA6 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg16 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA6 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX6 天前
020-C++之unordered容器
数据结构·c++
岛雨QA6 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas6 天前
初识基本排序
java·数据结构·学习方法·排序