java贪心算法最优装箱问题
时间: 2023-12-02 13:43:25 浏览: 175
以下是Java中使用贪心算法解决最优装箱问题的代码示例:
```java
import java.util.Arrays;
public class OptimalPacking {
public static void main(String[] args) {
int[] weights = {5, 10, 2, 4, 1};
int capacity = 12;
int maxBoxes = getMaxBoxes(weights, capacity);
System.out.println("The maximum number of boxes that can be loaded is: " + maxBoxes);
}
public static int getMaxBoxes(int[] weights, int capacity) {
Arrays.sort(weights); // 将集装箱按重量从小到大排序
int maxBoxes = 0;
int currentWeight = 0;
for (int i = 0; i < weights.length; i++) {
if (currentWeight + weights[i] <= capacity) { // 如果当前重量加上集装箱i的重量不超过载重量c
currentWeight += weights[i]; // 将集装箱i装上轮船
maxBoxes++; // 装箱数加1
} else {
break; // 如果装不下了,退出循环
}
}
return maxBoxes;
}
}
```
阅读全文