0.1) 本文總結於 數據結構與算法分析, 源代碼均爲原創, 旨在 理解 「近似裝箱問題(兩種脫機算法實現)」 的idea 並用源代碼加以實現;
0.2) 近似裝箱問題的兩種聯機算法 分別是: 首次適合遞減算法 和 最佳適合遞減算法 , 咱們將依次給出源代碼實現+算法描述;
0.3)聯機算法+脫機算法git
1.0)聯機算法的主要問題:在於將大項物品裝箱困難, 特別是當他們在輸入的晚期出現的時候,
1.1)圍繞這個問題的天然方法:將各項物品排序,把最大的物品放在最早,此時咱們能夠應用首次適合算法或最佳適合算法,分別獲得 「首次適合遞減算法」 和 」最佳適合遞減算法」;
1.2)看個荔枝(能夠產生的最優解):
1.3)咱們能夠證實的結論有(Conclusion):github
2.1)download source code: https://github.com/pacosonTang/dataStructure-algorithmAnalysis/tree/master/chapter10/p274_firstFitDecreaseTen
2.2)source code at a glance:(for complete code , please click the given link above)算法
int main() { ElementTypePtr tempBox; int tempKey; int key[7] = {2, 5, 4, 7, 1, 3, 8}; int i; size = 7; initBox(size); surplus = buildBasicArray(size, 10); // building surplus array to store surplus value tempBox = buildSingleElement(); bh = initBinaryHeap(size + 1); for(i=0; i<size; i++) { tempBox->key = key[i]; insertHeap(*tempBox, bh); }// building binary heap over printBinaryHeap(bh); printf("\n"); printf("\n===the sequence deleting minimum from binary heap===\n"); while(!isEmpty(bh)) { tempKey = deleteMin(bh)->key; printf("%d -> ", tempKey); firstFixDecrease(tempKey); } printf("\n"); printBox(size); return 0; } void firstFixDecrease(int key) { int i; ElementTypePtr box; ElementTypePtr temp; box = buildSingleElement(); box->key = key; // build single box with key over for(i=0; i<size; i++) { if(surplus[i] < key) continue; else break; } temp = boxes[i] ; while(temp->next) temp = temp->next; temp->next = box; surplus[i] -= key; }
2.3)printing results:
數據結構
3.1)download source code: https://github.com/pacosonTang/dataStructure-algorithmAnalysis/tree/master/chapter10/p274_bestFitDecreaseTen
3.2)source code at a glance:(for complete code , please click the given link above)ide
int main() { ElementTypePtr tempBox; int tempKey; int key[7] = {2, 5, 4, 7, 1, 3, 8}; int i; size = 7; initBox(size); surplus = buildBasicArray(size, 10); // building surplus array to store surplus value tempBox = buildSingleElement(); bh = initBinaryHeap(size + 1); for(i=0; i<size; i++) { tempBox->key = key[i]; insertHeap(*tempBox, bh); }// building binary heap over printBinaryHeap(bh); printf("\n"); printf("\n===the sequence deleting minimum from binary heap===\n"); while(!isEmpty(bh)) { tempKey = deleteMin(bh)->key; printf("%d -> ", tempKey); bestFixDecrease(tempKey); } printf("\n"); printBox(size); return 0; } void bestFixDecrease(int key) { int i; ElementTypePtr box; ElementTypePtr temp; int minimum; int miniIndex; box = buildSingleElement(); box->key = key; // build single box with key over miniIndex = 0; minimum = 10; for(i=0; i<size; i++) { if(surplus[i] < key) continue; if(surplus[i] - key < minimum) { minimum = surplus[i] - key; miniIndex = i; } } temp = boxes[miniIndex] ; while(temp->next) temp = temp->next; temp->next = box; surplus[miniIndex] -= key; }
3.3)printing results:
測試