[二叉堆] 洛谷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;
}

猜你喜欢

转载自blog.csdn.net/icecab/article/details/81513772