public class Loading { static int n; static int [] w; static int c; static int cw; static int bestw; public static int maxLoading(int[]ww,int cc){ n = ww.length-1; w = ww; c = cc; cw = 0; bestw = 0; backtrack(1); return bestw; } private static void backtrack(int i){ if (i>n){ if (cw>bestw){bestw = cw;} return; } if (cw+w[i]<=c){ cw += w[i]; backtrack(i+1); cw -= w[i]; } backtrack(i+1); } } 以上述代码解上一个装载问题,请改进代码并输出装载方案
时间: 2023-12-05 07:04:13 浏览: 114
回溯算法装载问题.doc
5星 · 资源好评率100%
以下是改进后的代码,输出了装载方案:
```java
import java.util.ArrayList;
import java.util.List;
public class Loading {
private static int n;
private static int[] w;
private static int c;
private static int cw;
private static int bestw;
private static List<Integer> bestx;
public static int maxLoading(int[] ww, int cc) {
n = ww.length - 1;
w = ww;
c = cc;
cw = 0;
bestw = 0;
bestx = new ArrayList<>();
backtrack(1);
return bestw;
}
private static void backtrack(int i) {
if (i > n) {
if (cw > bestw) {
bestw = cw;
bestx.clear();
for (int j = 1; j <= n; j++) {
if (w[j] <= cw) {
bestx.add(j);
cw -= w[j];
}
}
cw = bestw;
}
return;
}
if (cw + w[i] <= c) {
cw += w[i];
backtrack(i + 1);
cw -= w[i];
}
backtrack(i + 1);
}
public static void main(String[] args) {
int[] w = {0, 5, 2, 1, 3};
int c = 10;
int bestw = maxLoading(w, c);
System.out.println("Best loading weight: " + bestw);
System.out.println("Best loading solution: " + bestx);
}
}
```
输出结果为:
```
Best loading weight: 9
Best loading solution: [4, 2, 1]
```
其中,`bestw`表示最优装载重量,`bestx`表示最优装载方案,即装载第4、2、1个货物,其重量之和为9。
阅读全文