题目:最优装载问题:
一条小船用来运输货物到河对岸。假设船的最大载重量为MAXWEIGHT,每件货物的重量为 weight[i],怎么能够装载最多数量的货物到船上呢?
package Greedy_algorithm;
import java.util.Arrays;
/**
* 2023/10/31
*/
public class Loading {
public static void main(String[] args) {
int[] weight={10,15,8,12,14,9,11,7,13};
int weightMax=30;
int[] result=maxLoading(weight,weightMax);
System.out.println("可运载的货物重量为:");
for(int x:result){//增强for循环遍历
if (x!=0)//当数组中的数不为0时输出出来
System.out.print(x+" ");
}
}
public static int[] maxLoading(int[] weight,int weightMax){
int[] res=new int[weight.length];//定义结果数组
Arrays.sort(weight);//对重量进行排序
int cnt=weight[0];
for (int i=0;i<res.length-1;i++){
if (cnt<=weightMax){//如果总重量未达到最大值,就继续增重
res[i]=weight[i];
cnt+=weight[i+1];
}
if (cnt>weightMax)
break;
}
return res;
}
}
可运载的货物重量为:
7 8 9
进程已结束,退出代码为 0