1167. lowest cost connection bars

Title Description

To decorate the house, you need to process some of the length of the rod is a positive integer sticks.
If you want to lengths of X and Y are two bars together, you need to pay the cost of X + Y. Due to construction needs, you have to connect all the bars into one.
You return the lowest cost to all bars sticks together into a need. Note that you can choose the order of the bar connection.
Example 1:
Input: sticks = [2,4,3]
Output: 14
Explanation: 2 and 3 are connected to the first 5, it takes 5; and then 5 9 4 connected; total cost of 14.
Example 2:

Input: sticks = [1,8,3,5]
Output: 30

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

Thinking

Cost per selection least two remaining connecting rod, consider the priority queue - min-heap solved.

#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;
}

Guess you like

Origin www.cnblogs.com/wangcl97/p/12500837.html