题意:You have some sticks with positive integer lengths.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
思路:由于越开始拼接的棍棒使用次数越多,被累加的次数也越多,从而会让整体成本上升,我们可以每次拼接时,选取当前棍棒里长度最短的,这样成本会相对最低。
代码思路:构建最小堆(堆顶为最小元素), 每次弹出的都是堆中的最小值。
算法复杂度分析:N*logN
代码:
private static int findMinCost(int[] a) {
for (int i = 0; i < a.length; i++) {
heapInsert(a, i); //构建堆,从尾部插入
}
int size = a.length, res = 0, precious = a[0];
boolean used = false;
swap(a, 0, --size);//将根节点与最后一个节点交换,size--,相当于删去根节点
//逐步删除根节点
while (size > 0) {
heapify(a, 0, size); // 堆重构
if (used) {
precious = a[0];
swap(a, 0, --size);//将根节点与最后一个节点交换,size--,相当于删去根节点
} else {
res += precious + a[0]; // 当前最小的两个数求和
a[0] = precious + a[0]; // 替换
}
used = !used;
}
return res;
}
//重构堆(index为起始位置,size为节点数目,相当于终止位置的后一位置)
public static void heapify(int[] arr, int index, int size) {
int left = index * 2 + 1;//当前节点的左孩子,left+1为右节点index
while (left < size) {
int smallest = left + 1 < size && arr[left + 1] < arr[left] ? left + 1 : left;//左右孩子中较小孩子的下标
smallest = arr[smallest] < arr[index] ? smallest : index;//当前节点与最小孩子比较,找到最小值的下标
if (smallest == index) {
break;//当前节点就是最小值,不用继续重构堆了,直接返回
}
swap(arr, smallest, index);//有比自己xiao的孩子,交换
index = smallest;//当前节点变为比自己xiao的孩子
left = index * 2 + 1;//更新左孩子index
}
}
public static void heapInsert(int[] arr, int index) {
while (arr[index] < arr[(index - 1) / 2])//节点值大于父节点
{
swap(arr, index, (index - 1) / 2);
index = (index - 1) / 2;//节点变为父节点
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}