修理牧场(算最少锯木费用)

【问题描述】农夫要修理牧场的一段栅栏,他测量了栅栏,发现需要N块木头,每块木头长度为整数Li个长度单位,于是他购买了一条很长的、能锯成N块的木头,即该木头的长度是Li的总和。但是农夫自己没有锯子,请人锯木的酬金跟这段木头的长度成正比。为简单起见,不妨就设酬金等于所锯木头的长度。例如,要将长度为20的木头锯成长度为8、7和5的三段,第一次锯木头花费20,将木头锯成12和8;第二次锯木头花费12,将长度为12的木头锯成7和5,总花费为32。如果第一次将木头锯成15和5,则第二次锯木头花费15,总花费为35(大于32)。请编写程序帮助农夫计算将木头锯成N块的最少花费。

【输入形式】输入首先给出正整数N(≤104),表示要将木头锯成N块。第二行给出N个正整数(≤50),表示每段木块的长度。

【输出形式】输出一个整数,即将木头锯成N块的最少花费。

【样例输入】
8
4 5 1 2 1 3 1 1

【样例输出】
49

代码如下(用C编写):

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef long long ll;

// 最小堆结构
typedef struct {
    ll *data;
    int size;
    int capacity;
} MinHeap;

// 初始化堆
MinHeap* create_heap(int cap) {
    MinHeap *h = (MinHeap*)malloc(sizeof(MinHeap));
    h->data = (ll*)malloc(sizeof(ll) * (cap + 1));  // 1-based
    h->size = 0;
    h->capacity = cap;
    return h;
}

// 释放堆
void free_heap(MinHeap *h) {
    free(h->data);
    free(h);
}

// 向最小堆中插入元素
void heap_push(MinHeap *h, ll x) {
    if (h->size == h->capacity) return; // 已满
    h->size++;
    int i = h->size;
    // 上浮
    while (i > 1 && h->data[i/2] > x) {
        h->data[i] = h->data[i/2];
        i /= 2;
    }
    h->data[i] = x;
}

// 从最小堆中弹出最小值
ll heap_pop(MinHeap *h) {
    if (h->size == 0) return 0;
    ll ret = h->data[1];
    ll x = h->data[h->size--];
    // 下沉
    int i = 1, child;
    while (i*2 <= h->size) {
        child = i*2;
        if (child+1 <= h->size && h->data[child+1] < h->data[child]) {
            child++;
        }
        if (h->data[child] < x) {
            h->data[i] = h->data[child];
            i = child;
        } else {
            break;
        }
    }
    h->data[i] = x;
    return ret;
}

int main() {
    int N;
    if (scanf("%d", &N) != 1) return 0;

    MinHeap *h = create_heap(N);
    for (int i = 0; i < N; i++) {
        ll len;
        scanf("%lld", &len);
        heap_push(h, len);
    }

    ll total_cost = 0;
    // 不断取出最小的两段合并,直到堆中只剩一段
    while (h->size > 1) {
        ll a = heap_pop(h);
        ll b = heap_pop(h);
        ll c = a + b;
        total_cost += c;
        heap_push(h, c);
    }

    printf("%lld\n", total_cost);

    free_heap(h);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值