数据结构——哈夫曼树

可参考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;
}
相关推荐
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐1 天前
算法之常见八大排序
数据结构·算法·排序算法
tju新生代魔迷1 天前
数据结构:双向链表
数据结构·链表
songx_991 天前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子1 天前
数据结构——双向链表
c语言·数据结构·链表
Boop_wu1 天前
[数据结构] 栈 · Stack
数据结构
kk”1 天前
C语言快速排序
数据结构·算法·排序算法
3壹1 天前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
papership1 天前
【入门级-算法-6、排序算法:选择排序】
数据结构·算法·排序算法
YS_Geo1 天前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis