荷马史诗 二叉堆 哈夫曼树 2022.3.10

122 阅读1分钟

考研算法

题目

题目链接

题目要求

给定权值,实现一个K叉树(K也为给定)
输出最小带全树的权值及深度

代码

#include <iostream>
#include <queue>
using namespace std;
typedef long long LL;
typedef pair<LL,int> PLI;
int main()
{
    int n,k;
    cin>>n>>k;
    priority_queue<PLI,vector<PLI>,greater<PLI>> h;//小根堆
    for (int i=0;i<n;i++)
    {
        LL w;
        cin>>w;
        h.push({w,0});
    }
    while ((n-1)%(k-1))//为了防止对生成的k叉树不是完全树,不是完全树会对结果有影响
    {
        n++;
        h.push({0,0});
    }
    LL res=0;
    while(h.size()>1)
    {
        LL s=0;
        int d=0;
        for (int i=0;i<k;i++)
        {
            PLI p=h.top();
            s+=p.first;
            d=max(d,p.second);//得到当前最小的k个数中的最大深度
            h.pop();
        }
        res+=s;
        h.push({s,d+1});
    }
    cout<<res<<endl<<h.top().second<<endl;
}
from heapq import *
h=[]
n,k=map(int,input().split())
for _ in range(n):
    x=int(input())
    heappush(h,(x,0))
while ((n-1)%(k-1)):
    n+=1
    heappush(h,(0,0))
res=0
while(len(h)>1):
    s=0
    d=0
    for i in range(k):
        ite=heappop(h)
        s+=ite[0]
        d=max(d,ite[1])
    res+=s
    heappush(h,(s,d+1))
rres=heappop(h)
print(res)
print(rres[1])

知识点

pair and priority_queue

typedef pair<LL,int> PLI;
我理解为C++的一种数据结构,和struct类似
C++ pair的基本用法总结(整理)_sevenjoin的博客-CSDN博客_c++ pair priority_queue<PLI,vector<PLI>,greater<PLI>> h;
priority_queue为小根堆,我也认为是C++内部的一个数据结构

heapq

heapq为python内的一个库,可以帮助我们实现c++中小根堆的功能
heapq — 堆队列算法 — Python 3.7.12 文档
python3中的heapq模块使用 - 知乎 (zhihu.com)
(1条消息) python高级(堆heapq模块)_jamfiy的博客-CSDN博客_python 堆
Python标准库模块之heapq - 简书 (jianshu.com)