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:
测试