1.基本思想:
貪心算法是通過一系列的選擇來得到問題的解,它所做的選擇都是當前情況下最優的選擇,即貪心算法並不考慮整體最優,而考慮的是當前情況下的局部最優,即貪心選擇。
2.貪心算法的兩個性質:
1)貪心選擇性質:所求解的問題的整體最優解可以通過一系列局部最優的選擇來,即貪心選擇達到。貪心選擇所依賴的是以前所做過的選擇,而對以后所做的選擇沒有關系。
2)最優子結構性質:一個問題的最優解包含其子問題的最優解。
3.貪心算法與動態規划的區別:
動態規划是通過自底向上的方式解決子問題,貪心算法是通過自頂向下的迭代方式做出貪心選擇,求解問題的最優解。兩共同點是都具有最優子結構性質。
4.最優裝載問題:采用重量最輕者先裝載的貪心選擇策略。
1 #include "stdafx.h" 2 #include <iostream> 3 using namespace std; 4 const int N = 4; 5 template <class type> 6 void Swap(type &x, type &y){ 7 type temp = x; 8 x = y; 9 y = temp; 10 } 11 void BubleSort(int w[],int t[], int n){ 12 for (int i = 1; i <= n; i++) 13 { 14 t[i] = i; 15 } 16 17 for (int i = 1; i < n; i++) 18 { 19 int temp = i; 20 for (int j =i+1; j <= n; j++){ 21 if (w[temp]>w[j]) 22 { 23 temp = j; 24 Swap(w[i], w[j]); 25 } 26 } 27 Swap(t[i], t[temp]); 28 } 29 } 30 void BestLoad(int w[], int x[],int c, int n){ 31 32 int t[N + 1] = {0};//記錄原始索引 33 BubleSort(w, t, N); 34 for (int i = 1; i <= n; i++) 35 { 36 x[i] = 0; 37 } 38 for (int i = 1; i <= n&& w[t[i]] <= c; i++) 39 { 40 x[t[i]] = 1; 41 c -= w[t[i]]; 42 } 43 } 44 int main(){ 45 int c = 50; 46 int w[] = { 0, 20,10,25,15 }; 47 int x[N + 1]; 48 cout << "載重容量為:\n" << c << endl; 49 cout << "物品的重量分別為:" << endl; 50 for (int i = 1; i <= N; i++) 51 { 52 cout << w[i] << " "; 53 } 54 cout << endl; 55 BestLoad(w,x, c, N); 56 cout << "貪心選擇結果為:" << endl; 57 for (int i = 1; i <= N; i++) 58 { 59 cout << x[i] << " "; 60 } 61 cout << endl; 62 }