ybtoj+D. 【例题4】荷马史诗 (树形数据结构+贪心)

思路:观看此题,脑海中第一时间就想到了trie树;

方案:构建出一个类似于trie树的树,之后对其进行移动子树操作,使整棵树的最大深度最小;

使用结构:大根堆,维护一个每个子节点的数值与深度,从深到浅将每个节点的子节点的数值合并在父节点上,最后输出根的深度;

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef long long LL;
struct GG {
    LL val, dep;
    bool operator<(const GG& t) const {
        if (val == t.val)
            return dep > t.dep;//构建一颗树,从深到浅
        return val > t.val;//将数值排序,使其成为最优解
    }
};
LL res = 0, cnt = 0;
priority_queue<GG> heap;//堆来维护
int main() {
    int n, k;
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        LL t;
        cin >> t;
        heap.push({ t, 0 });//将节点加入堆
    }
    cnt = n;
    if ((n - 1) % (k - 1) != 0)
        cnt += k - 1 - (n - 1) % (k - 1);//剪切子树操作
    for (int i = 1; i <= cnt - n; i++) {
        heap.push({ 0, 0 });//加入空节点,使其平衡
    }
    while (cnt != 1) {
        LL val = 0, deep = 0;
        for (int i = 1; i <= k; i++) {
            auto tot = heap.top();
            val += tot.val;
            deep = max(deep, tot.dep);//合并
            heap.pop();
        }
        heap.push({ val, deep + 1 });
        cnt -= k - 1;
        res += val;//答案
    }
    cout << res << endl << heap.top().dep << endl;
    return 0;
}

 

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值