运用贪心算法求解最优装载问题
实验目的:
1) 掌握贪心算法的设计思想;
2)掌握贪心算法解题步骤;
3)学习运用贪心算法分析并解决最优装载问题。
实验要求:
例:设有一小货轮载重量为30,待装集装箱有8个,其重量分别为[4,10,7,11,3,5,14,2],问最多能装入的集装箱数量。
实验内容:
有n个集装箱要装上一艘载重量为W的轮船,其中集装箱i(1<=i<=n)的重量为wi。不考虑集装箱的体积限制,现要选出尽可能多的集装箱上轮船,使得它们的重量之和不超过W。
要求装载的物品的数量尽可能多,而船的容量是固定的,那么优先把重量小的物品放进去,在容量固定的情况下,装的物品最多。采用重量最轻者先装的贪心选择策略,从局部最优达到全局最优,从而产生最优装载问题的最优解。
实验步骤:
第一个
package sf;
import javax.lang.model.element.Element;
import java.util.Arrays;
import java.util.Scanner;
public class Loading1 {
private static int[] x;
public static float Loading(float c, float[] w, int[] x) {
int n = w.length;
Element[] d = new Element[n];
for (int i = 0; i < n; i++) {
// 初始化
d[i] = new Element(w[i], i);
}
Arrays.sort(d);
// 记录最优值
float opt = 0;
for (int i = 0; i < n; i++) {
// 初始化
x[i] = 0;
}
for (int i = 0; i < n && d[i].w <= c; i++) {
x[d[i].i] = 1;
opt += d[i].w;
c -= d[i].w;
}
return opt;
}
public static void main(String[] args) {
System.out.println("请输入载重量c:");
Scanner sc = new Scanner(System.in);
float c = sc.nextInt();
System.out.println("集装箱个数:");
int n = sc.nextInt();
System.out.println("请输入每个集装箱的重量:");
float[] w = new float[n];
for (int i = 0; i < n; i++) {
w[i] = sc.nextInt();//输入每个物品的重量
}
Arrays.sort(w);//按集装箱重量升序排序
System.out.println("排序后的重量为:");
for (float i: w) {
System.out.print(i+" ");
}
System.out.println();
int tmp = 0;//tmp为已装载到船上的集装箱重量
int ans = 0;//ans为已装载到船上的集装箱重量
for (int i = 0; i < n; i++){
tmp += w[i];
if (tmp <= c)
ans ++;
else
break;
}
System.out.println("能装入的集装箱最大数量为:" + ans);
//float[] w = new float[]{4,10,7,11,3,5,14,2};
x = new int[w.length];
float opt = Loading(c, w, x);
System.out.println("最优值为: " + opt);
System.out.println("最优解为: " + Arrays.toString(x));
}
public static class Element implements Comparable<Element> {
float w;
int i;
public Element(float w, int i) {
this.w = w;
this.i = i;
}
/**
* 按照升序排列
*/
@Override
public int compareTo(Element o) {
if (this.w < o.w)
return -1;
else if (this.w == o.w)
return 0;
else
return 1;
}
}
}
第二个
package sf;
import java.util.Arrays;
import java.util.Scanner;
//实验五 贪心算法 装载问题
public class loading {
public static void main(String[] args) {
System.out.println("请输入载重量c:");
Scanner sc = new Scanner(System.in);
double c = sc.nextDouble();
System.out.println("集装箱个数:");
int n = sc.nextInt();
System.out.println("请输入每个集装箱的重量:");
int[] w = new int[n];
for (int i = 0; i < n; i++) {
w[i] = sc.nextInt();//输入每个物品的重量
}
Arrays.sort(w);//按集装箱重量升序排序
System.out.println("排序后的重量为:");
for (int i: w) {
System.out.print(i+" ");
}
System.out.println();
int tmp = 0;//tmp为已装载到船上的集装箱重量
int ans = 0;//ans为已装载到船上的集装箱重量
for (int i = 0; i < n; i++){
tmp += w[i];
if (tmp <= c)
ans ++;
else
break;
}
System.out.println("能装入的集装箱最大数量为:" + ans);
}
}
实验结果:
第一个
第二个
实验小结