貪心算法思想:不從整體最優上加以考慮,它所做出的選擇只是在某種意義上的局部最優選擇,當然希望貪心算法得到的最終結果也是整體最優的;
貪心算法性質:指所求問題的整體最優解可以通過一系列局部最優的選擇,即貪心選擇來達到;
最優裝載問題
(1)問題描述:有一批集裝箱要裝上一艘載重量為 tatol 的輪船,其中集裝箱 index 的重量為 weight。最優裝載問題要求在裝載體積不受限制的情況下,將盡可能多的集裝箱裝上輪船【目前只考慮一個物品只有一個】,store 數組存放物品是否裝載 1:存放 0:不存放;
(2)最優裝載問題可用貪心算法求解,采用重量最輕者先裝的貪心選擇策略,可產生最優裝載問題的最優解,算法如下:
public class ExcellentLoading { /** * 輪船的最大容量 */ private static Integer total = 0; /** * 輪船裝完物品,剩余重量 */ private static Integer residueTotal = 0; /** * 裝入的物品個數 */ private static Integer num = 0; /** * 物品重量數組 */ private static Integer[] weight; /** * 物品存放數組【1:存放 0:不存放】 */ private static Integer[] store; /** * 初始化數據 */ private static void initData() { Scanner input = new Scanner(System.in); System.out.print("請輸入輪船的總重量:"); total = input.nextInt(); System.out.print("請輸入要裝入的物品個數:"); num = input.nextInt(); System.out.println("請輸入各物品的重量:"); weight = new Integer[num]; store = new Integer[num]; for (int i = 0; i < weight.length; i++) { weight[i] = input.nextInt(); //每個物品的重量 store[i] = 0; //初始化物品都不存放 } } /** * 按物品重量由小到大升序排序,同時調整物品序號 */ private static void weightSort() { Integer change = 1; Integer temp; for (int i = 0; i < weight.length - 1 && change == 1; i++) { change = 0; for (int j = 0; j < weight.length - 1 - i; j++) { if (weight[j] > weight[j + 1]) { // 交換重量數組 temp = weight[j]; weight[j] = weight[j + 1]; weight[j + 1] = temp; change = 1; //避免不必要的排序操作 } } } } /** * 統計最優裝載 */ private static void excellentLoading() { residueTotal = total; for (int i = 0; i < weight.length && weight[i] <= residueTotal; i++) { store[i] = 1; // 輪船存放物品 residueTotal = residueTotal - weight[i]; // 輪船剩余重量 } } /** * 輸出函數 */ private static void print() { System.out.println("輪船最大容量: total = " + total + ",輪船剩余容量: residueTotal = " + residueTotal); System.out.println("排序完物品數組: "); Stream.of(weight).forEach(element -> System.out.print(element + " ")); System.out.println(); System.out.println("物品存放數組: "); Stream.of(store).forEach(element -> System.out.print(element + " ")); System.out.println(); } public static void main(String[] args) { // 初始化數據 initData(); // 排序【按重量由小到大】 weightSort(); // 統計最優裝載 excellentLoading(); // 輸出 print(); } }
(3)輸入輸出結果:
請輸入輪船的總重量:20 請輸入要裝入的物品個數:6 請輸入各物品的重量: 1 4 8 6 9 3 輪船最大容量: total = 20,輪船剩余容量: residueTotal = 6 排序完物品數組: 1 3 4 6 8 9 物品存放數組: 1 1 1 1 0 0
(4)總結:貪心算法重在考慮局部最優解,整體最優解即在眾多個局部最優解中選擇一個最優的解;