0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在 理解 “近似装箱问题(两种脱机算法实现)” 的idea 并用源代码加以实现;
0.2) 近似装箱问题的两种联机算法 分别是: 首次适合递减算法 和 最佳适合递减算法 , 我们将依次给出源代码实现+算法描述;
0.3)联机算法+脱机算法
1.0)联机算法的主要问题:在于将大项物品装箱困难, 特别是当他们在输入的晚期出现的时候,
1.1)围绕这个问题的自然方法:将各项物品排序,把最大的物品放在最先,此时我们可以应用首次适合算法或最佳适合算法,分别得到 “首次适合递减算法” 和 ”最佳适合递减算法”;
1.2)看个荔枝(可以产生的最优解):
1.3)我们可以证明的结论有(Conclusion):
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;
}
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)
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;
}