数据结构——哈夫曼树

可参考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;
}
相关推荐
liu****18 分钟前
一.脚手架介绍以及部分工具使用
开发语言·数据结构·c++·手脚架开发
历程里程碑1 小时前
C++ 6 :string类:高效处理字符串的秘密
c语言·开发语言·数据结构·c++·笔记·算法·排序算法
xu_yule1 小时前
算法基础-(数据结构)
数据结构
玩转数据库管理工具FOR DBLENS1 小时前
DBLens:开启数据库管理新纪元——永久免费,智能高效的国产化开发利器
数据结构·数据库·测试工具·数据库开发
@小码农2 小时前
2025年全国青少年信息素养大赛 Gandi编程 小低组初赛真题
数据结构·人工智能·算法·蓝桥杯
六毛的毛2 小时前
重排链表问题
数据结构·链表
Fine姐2 小时前
数据结构——02队列
数据结构
仰泳的熊猫3 小时前
1176 The Closest Fibonacci Number
数据结构·c++·算法·pat考试
一条大祥脚3 小时前
Cuda Rudece算子实现(附4090/h100测试)
java·数据结构·算法
2401_841495643 小时前
【LeetCode刷题】跳跃游戏
数据结构·python·算法·leetcode·游戏·贪心算法·数组