解题步骤
首先将n个集装箱依其重量从小到大排序。
然后依此顺序将集装箱装上轮船,直到不能装为止。
package com.hhmstu.Algorithmdesignandanalysis.Greedyalgorithm; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Comparator; public class Optimal_loading { public static void main(String[] args) { int c = 70; int[][] w = {{1, 20}, {2, 10}, {3, 26}, {4, 15}}; int[] m = new int[4]; ol(c, w, m); System.out.println("要装的集装箱号为:"); for (int i = 0; i < m.length; i++) { if (m[i] != 0) { System.out.print(m[i] + "\t"); } } } public static void ol(int c, int[][] w, int[] m) { Arrays.sort(w, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[1] - o2[1]; } }); for (int i = 0; i < w.length; i++) { if (w[i][1] <= c) { m[i] = w[i][0]; c -= w[i][1]; } } } }