1167. 连接棒材的最低费用

题目描述

为了装修新房,你需要加工一些长度为正整数的棒材 sticks。
如果要将长度分别为 X 和 Y 的两根棒材连接在一起,你需要支付 X + Y 的费用。 由于施工需要,你必须将所有棒材连接成一根。
返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序。
示例 1:
输入:sticks = [2,4,3]
输出:14
解释:先将 2 和 3 连接成 5,花费 5;再将 5 和 4 连接成 9;总花费为 14。
示例 2:

输入:sticks = [1,8,3,5]
输出:30

提示:
1 <= sticks.length <= 10^4
1 <= sticks[i] <= 10^4

思路

每次选择剩余棒材中费用最少的两根进行连接,考虑使用优先队列--最小堆来解决。

#include <stdlib.h>
#include <stdio.h>
#define MinData 0;
typedef int ElementType;
typedef struct HNode{
    ElementType *data;
    int size;
    int capacity;
}*Heap;
typedef Heap MinHeap;

MinHeap CreateHeap(int size){
    MinHeap heap = (MinHeap)malloc(sizeof(struct HNode));
    heap->data = (ElementType *)malloc(sizeof(ElementType)*(size+1));
    heap->size = 0;
    heap->capacity = size;
    heap->data[0] = MinData;
    return heap;
}

void InsertMinHeap(MinHeap heap, ElementType x){
    if(heap->size == heap->capacity)
        return;
    int pos = ++heap->size;
    for(; heap->data[pos/2]>x; pos/=2){
        heap->data[pos] = heap->data[pos/2];
    }
    heap->data[pos] = x;
}

ElementType DeleteFromMinHeap(MinHeap heap){
    if(heap->size==0){
        return heap->data[0];
    }
    int top = heap->data[1];
    int last = heap->data[heap->size--];
    int parent,child;
    for(parent=1; parent*2<=heap->size;parent=child){
        child = parent*2;
        if(child!=heap->size&&heap->data[child]>heap->data[child+1]){
            child++;
        }
        if(last>heap->data[child]){
            heap->data[parent]=heap->data[child];
        }
        else {
            break;
        }
    }
    heap->data[parent]=last;
    return top;
}

int connectSticks(int* sticks, int sticksSize){
    int x1,x2,cost=0,sum=0;
    MinHeap heap= CreateHeap(sticksSize);
    for(int i=0;i<sticksSize;i++){
        InsertMinHeap(heap,sticks[i]);
    }
    while(heap->size!=0){
        x1=DeleteFromMinHeap(heap);
        cost=x1;
        if(heap->size==0){
            break;
        }
        else{
            x2=DeleteFromMinHeap(heap);
            cost+=x2;
            InsertMinHeap(heap,cost);
            sum+=cost;
        }
    }
    return sum;
}

猜你喜欢

转载自www.cnblogs.com/wangcl97/p/12500837.html