数据结构——哈夫曼树

可参考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;
}
相关推荐
磊 子2 小时前
笔试面试中关于链表相关的题目
数据结构·链表·面试·职场和发展
Genevieve_xiao8 小时前
【数据结构】【xjtuse】八股文单元小测
数据结构·算法
想唱rap10 小时前
Linux下进程的状态和优先级
linux·运维·服务器·开发语言·数据结构·算法
Croa-vo11 小时前
逆袭Akuna Quant!美硕秋招亲历,从网申到拿offer全攻略
数据结构·经验分享·算法·面试·职场和发展
vir0212 小时前
交换瓶子(贪心)
数据结构·算法
9523613 小时前
数据结构-二叉树
java·数据结构·学习
HUTAC14 小时前
重要排序算法(更新ing)
数据结构·算法
冉佳驹14 小时前
数据结构 ——— 八大排序算法的思想及其实现
c语言·数据结构·排序算法·归并排序·希尔排序·快速排序·计数排序
Hello_Embed15 小时前
FreeRTOS 入门(四):堆的核心原理
数据结构·笔记·学习·链表·freertos·
烧冻鸡翅QAQ16 小时前
考研408笔记——数据结构
数据结构·笔记·考研