[二叉堆] 洛谷P1090 合并果子

题目

LP1090

思路

本题需要画一下图
这里写图片描述
可以观察到:
每个果子的代价:重量*在树中深度
考虑如果构造一个深度越深的结点权值越小,就能达到最小权值。那么本题的做法就变成了每次选最小的两堆果子合并。这个可以用二叉堆来做。

代码

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <cstring>
#define _for(i,a,b) for(int i = a; i<b; i++)
#define _rep(i,a,b) for(int i = a; i<=b; i++)
using namespace std;

const int maxn = 10000+10;
int n, t[maxn], cc;

void add(int x){
    t[++cc] = x;
    int now = cc, fa = cc/2;
    while(fa && t[now] < t[fa]){
        swap(t[now], t[fa]);
        now = fa;
        fa/=2;
    }
}

int del(){
    int res = t[1];
    t[1] = t[cc];
    cc--;
    int now = 1, ch = 2;
    if (ch < cc && t[ch] > t[ch+1]) ch++;
    while (ch <= cc && t[now] > t[ch]){
        swap(t[now], t[ch]);
        now = ch;
        ch*=2;
        if (ch < cc && t[ch] > t[ch+1]) ch++;
    }
    return res;
}

int main(){
    scanf("%d",&n);
    _for(i,0,n){
        int x;
        scanf("%d",&x);
        add(x);
    }
    int ans = 0, w = 0;
    _for(i,0,n-1){
        w = del()+del();
        add(w);
        ans+=w;
    }
    printf("%d\n",ans);

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值