初阶问题:(贪心算法求解)
(1)有N堆石子,现要将石子有序的合并成一堆,规定如下:每次只能移动任意的2堆石子合并,合并花费为新合成的一堆石子的数量。求将这N堆石子合并成一堆的最低花费
//有N堆石子,现要将石子有序的合并成一堆,
// 规定如下:
// 每次只能移动任意的2堆石子合并,合并花费为新合成的一堆石子的数量。求将这N堆石子合并的最低花费
//可以认为是一个森林变树的过程(哈夫曼树)
//贪心算法:将石子堆按石子数进行排序,每次取出最小值和次最小值进行归并
//将归并结果继续排序
public class Simple {
public static void main (String[] args) {
int[] arr = {1, 2, 2, 5, 8};
int cost = 0;//记录花费
//需要记录当前有几个数需要进行排序
int count = arr.length;
if (count > 1) qSort(arr, 0, count-1);
//这里使用快排还是太浪费了,使用插入排序比较合适。毕竟快排真正有效只在第一次比较时,之后都是有序的,只有一个数插入
while (count > 1){//需要归并n-1次
count--;
//取出最小的两个数相加,再放回
cost += arr[count]+arr[count-1];
iSort(arr, count-1, arr[count]+arr[count-1]);
}
System.out.print(cost);//输出最小花费次数
}
//需要一个排序来得到最小和次最小值
//选择使用快排(堆排或其他排序也行) --- 从大到小排
//快排需要选取一个目标数,目标数左边的数值都比其小,右边的都比他大
public static void qSort (int[] arr, int lf, int rt) {
int tmp = arr[lf];//选取左边第一个数作为快排目标数
int low = lf;
int high = rt;
while (low < high){
//从右往左比较,直到出现比目标数小的值
while (high > lf && arr[high] <= tmp)
high--;
if (arr[high] > tmp) {
arr[low] = arr[high];
low++;
}
//从左往右比较,直到出现比目标大的值
while (low < rt && arr[low] >= tmp)
low++;
if (arr[low] < tmp) {
arr[high] = arr[low];
high--;
}
}
//找到目标位置,存入
arr[low] = tmp;
//继续递归
if (low-1 > lf) {
qSort(arr, lf, low-1);
}
if (high+1 < rt) {
qSort(arr, high+1, rt);
}
}
public static void iSort (int[]arr, int len, int num) {
int poi = 0;
for (int i=0; i < len; i++){
if (arr[i] < num) break;
poi++;
}
//整体后挪
for (int i=len; i > poi; i--){
arr[len] = arr[len-1];
}
arr[poi] = num;
}
}