最優裝載問題(貪心法)
阿新 • • 發佈:2019-02-14
問題描述:
有一批集裝箱要裝上一艘載重量為c的輪船。其中集裝箱i的重量為Wi。最優裝載問題要求確定在裝載體積不受限制的情況下,將盡可能多的集裝箱裝上輪船。
問題可以描述為:
式中,變數xi = 0 表示不裝入集裝箱 i,xxi = 1 表示裝入集裝箱 i。
剛看到的時候,給我的感覺就像是排好序的揹包問題一樣,那麼問題就變得簡單了。
程式碼實現:
為了不改變原weight陣列中的順序,所以在函式中引入了一個臨時變數tempWeight來進行氣泡排序。
private static void load_problem(int[] weight, int c) {
int number = weight.length; // 商品數量
int[] tempWeight = weight; // 臨時陣列用於排序
int currentSpace = c; // 剩餘空間
// 氣泡排序:從小到大排序
for (int i = 0; i < number; i++) {
for (int j = i + 1; j < number; j++) {
if (tempWeight[i] > tempWeight[j]) {
tempWeight[i] = tempWeight[i] + tempWeight[j];
tempWeight[j] = tempWeight[i] - tempWeight[j];
tempWeight[i] = tempWeight[i] - tempWeight[j];
}
} // end inner for
} // end outer for
System.out.println("裝載物品如下:");
// 貪心選擇裝載
for (int i = 0; i < number; i++) {
if (tempWeight[i] > currentSpace) break;
currentSpace -= tempWeight[i];
System.out.printf("重量為:%2d\n", tempWeight[i]);
}
}