《数据结构、算法与应用C++语言描述》- 箱子装载问题-最大输者树实现最先适配法C++

箱子装载问题

完整可编译运行代码见:Github::Data-Structures-Algorithms-and-Applications/_32Box loading

问题描述

在箱子装载问题中,箱子的数量不限,每个箱子的容量为 binCapacity,待装箱的物品有n个。物品i需要占用的箱子容量为 o b j e c t S i z e [ i ] objectSize[i] objectSize[i] 0 ≤ o b j e c t S i z e [ i ] 0\leq objectSize[i] 0objectSize[i] ≤ b i n C a p a c i t y \leq binCapacity binCapacity

可行装载(feasible packing):所有物品都装入箱子而不溢出。

最优装载(optimal packing):使用箱子最少的可行装载。

**举例 例 13-4[卡车装载]**某一运输公司需把包裹装入卡车中,每个包裹都有一定的重量,每辆卡车都有载重限制(假设每辆卡车的载重都一样),如何用最少的卡车装载包裹,这是卡车装载问题。这个问题可以转化为箱子装载问题,卡车对应箱子,包裹对应物品。

箱子装载问题和机器调度问题一样,是NP-复杂问题,因此常用近似算法求解。求解所得的箱子数不是最少,但接近最少。

近似算法

最先适配法(First Fit,FF)

物品按 1,2,…,n 的顺序装入箱子。假设箱子从左至右排列。每一物品i放入可装载它的最左面的箱子。

最先适配递减法(First Fit Decreasing,FFD)

此方法与 FF 类似,区别在于,所有物品首先按所需容量的递减次序排列,即对于1 <i<n,有 objectSize[i]>objectSize[i+1]。

最优适配法(Best Fit,BF)

令bin[j].unusedCapacity为箱子j的可用容量。初始时,所有箱子的可用容量为binCapacity。物品i放入可用容量unusedCapacity最小但不小于objectSize[i]的箱子。

最优适配递减法(Best Fit Decreasing,BFD)

此法与BF相似,区别在于,所有物品首先按所需容量的递减的次序排列,即对于1 <i<n,有objectSize[i]>objectSize[i+1]。

定理13-1

设I为箱子装载问题的任一实例,b(I)为最优装载所用的箱子数。FF和BF所用的箱子数不会超过(17/10)b(I)+2,而FFD和BFD所用的箱子数不会超过(11/9)b(I)+4。

举例

例13-6 有4件物品,所需容量分别为objectSize[1:4]=[3,5,2,4],把它们放入容量为7的一组箱子中。

当使用FF 法时,物品 1 放入箱子 1;物品 2 放入箱子 2。因为箱子1 是可容纳物品3的最左面的箱子,所以物品3放入箱子1。物品4无法再放入前面用过的两个箱子,因此使用了一个新箱子。最后共用了三个箱子:物品 1 和 3 放入箱子 1;物品 2 放入箱子 2;物品 4 放入箱子 3。

当使用BF法时,物品 1 和 2 分别放入箱子 1 和箱子2。物品 3 放入箱子2,这比放入箱子1更能充分利用空间。物品4放入箱子1正好用完了空间。这种装载方案只用了两个箱子:物品1和4放入箱子1;物品2和3放入箱子2。

如果使用FFD和BFD方法,物品按2、4、1、3排序。最后结果一样:物品2和3放入箱子1;物品1和4放入箱子2。

最大输者树实现最先适配法

算法

最大输者树可以实现FF和FFD算法,时间复杂度为O(nlogn)。初始状态时,初始化n个箱子的容量为binCapacity,使用数组bin存储,然后将bin数组作为选手初始化最大输者树。对于每个物品,寻找合适的箱子存放。从根advance[1]的左孩子child=2开始搜索,查看左孩子的赢者内存是否足够,如果够执行下一步,反之,将child++,寻找右孩子;下一步沿着树的路径寻找当前孩子的左孩子,child*=2,while循环直到child>=n(其实也就是找到内部节点index最大的节点了)。撤销向最后的左孩子的移动,找到其父亲,child/=2。如果child<n,则找到了所求箱子节点binToUse的父亲节点child,寻找当前child的赢者,确保此赢者是最左面的箱子,将其作为binToUse;如果child>=n,说明遇到了n为基数的情况,n为基数时总有一个内部节点的比赛是内部节点和外部节点的比赛,child>=n的原因是前面定位到了外部节点,此时需要将child/=2定位到该外部节点的父节点,然后找到父节点的赢者,即右孩子,作为binToUse。找到binToUse后将物体放到binToUse箱子中,将该箱子的内存-=objectSize[i],重新组织比赛。

算法的时间复杂度为O(nlogn)。

/*
 * 最先适配算法的实现
 * objectSize数组存储物体的重量,objectSize[i]表示物体i的重量
 * numberOfObjects存储物体的数量
 * binCapacity存储初始时箱子的容量
 */
void firstFitPack(const int *objectSize, int numberOfObjects,
                  int binCapacity)
{
   // 初始状态下所有箱子都是空的,容量都为binCapacity。objectSize[1:numberOfObjects] = {binCapacity}

    int n = numberOfObjects;             // 物体的个数

    // 初始化输者树,箱子容量越大,就是胜者
    auto *bin = new int[n + 1];  // bins
    for (int i = 1; i <= n; i++)
        bin[i] = binCapacity;
    MaxmumLoserTree loserTreeObj(bin, n);
    // 将物体i打包到箱子中
    for (int i = 1; i <= n; i++)
    {
   
        // 寻找有足够内存的箱子
        int child = 2;  // 从根的左孩子开始搜索
        while (child < n)
        {
   
            int winner = loserTreeObj.getTheWinner(child);// 返回左孩子的赢者
            if (bin[winner] < objectSize[i]) // 左孩子的赢者内存不够,找右孩子
                child++;
            child *= 2;   // 找到当前孩子的左孩子,继续沿着树的路径往叶子节点走
        }

        int binToUse;          // 设置为要使用的箱子
        child /= 2;            // 撤销向最后的左孩子的移动,找到其父亲
        if (child < n)
        {
   
            binToUse = loserTreeObj.getTheWinner(child);
            // 保证binToUse是最左边的箱子
            if (binToUse > 1 && bin[binToUse - 1] >= objectSize[i])
                binToUse--;
        }
        else // 当n是奇数时,前面的while循环可能定位到 内部节点与外部节点比赛的外部节点,这样child就可能会>=n,这样的话就需要定位到该外部节点的父亲
            binToUse = loserTreeObj.getTheWinner(child / 2); // 既然前面的while循环定位到了该比赛(内部节点与外部节点比赛)的右孩子,说明左孩子不符合要求,一定是右孩子是赢者

        cout << "Pack object " << i << " in bin "
             << binToUse << endl;
        bin[binToUse] -= objectSize[i];
        loserTreeObj.rePlay(binToUse);
    }
}

代码

main.cpp

// first fit bin packing

#include <iostream>
#include "MaxmumLoserTree.h"
using namespace std;

// 最先适配算法的实现
/*
 * 最先适配算法的实现
 * objectSize数组存储物体的重量,objectSize[i]表示物体i的重量
 * numberOfObjects存储物体的数量
 * binCapacity存储初始时箱子的容量
 */
void firstFitPack(const int *objectSize, int numberOfObjects,
                  int binCapacity)
{
   // 初始状态下所有箱子都是空的,容量都为binCapacity。objectSize[1:numberOfObjects] = {binCapacity}

    int n = numberOfObjects;             // 物体的个数

    // 初始化输者树,箱子容量越大,就是胜者
    auto *bin = new int[n + 1];  // bins
    for (int i = 1; i <= n; i++)
        bin[i] = binCapacity;
    MaxmumLoserTree loserTreeObj(bin, n);
    loserTreeObj.output();
    // 将物体i打包到箱子中
    for (int i = 1; i <= n; i++)
    {
   
        // 寻找有足够内存的箱子
        int child = 2;  // 从根的左孩子开始搜索
        while (child < n)
        {
   
            int winner = loserTreeObj.getTheWinner(child);// 返回左孩子的赢者
            if (bin[winner] < objectSize[i]) // 左孩子的赢者内存不够,找右孩子
                child++;
            child *= 2;   // 找到当前孩子的左孩子,继续沿着树的路径往叶子节点走
        }

        int binToUse;          // 设置为要使用的箱子
        child /= 2;            // 撤销向最后的左孩子的移动,找到其父亲
        if (child < n)
        {
   
            binToUse = loserTreeObj.getTheWinner(child);
            // 保证binToUse是最左边的箱子
            if (binToUse > 1 && bin[binToUse - 1] >= objectSize[i])
                binToUse--;
        }
        else // 当n是奇数时,前面的while循环可能定位到 内部节点与外部节点比赛的外部节点,这样child就可能会>=n,这样的话就需要定位到该外部节点的父亲
            binToUse = loserTreeObj.getTheWinner(child / 2); // 既然前面的while循环定位到了该比赛(内部节点与外部节点比赛)的右孩子,说明左孩子不符合要求,一定是右孩子是赢者

        cout << "Pack object " << i << " in bin "
             << binToUse << endl;
        bin[binToUse] -= objectSize[i];
        loserTreeObj.rePlay(binToUse);
    }
}


// test program
int main()
{
   
// 测试最大输者树
//    int n;
//    cout << "Enter number of players, >= 2" << endl;
//    cin >> n;
//    if (n < 2)
//    {cout << "Bad input" << endl;
//        exit(1);}
//
//
//    int *thePlayer = new int[n + 1];
//
//    cout << "Enter player values" << endl;
//    for (int i = 1; i <= n; i++)
//    {
   
//        cin >> thePlayer[i];
//    }
//
//    MaxmumLoserTree<int> *w =
//            new MaxmumLoserTree<int>(thePlayer, n);
//    cout << "The loser tree is" << endl;
//    w->output();
    int n, binCapacity; // 物体的数量与箱子的容量
    cout << "Enter number of objects and bin capacity"
         << endl;
    cin >> n >> binCapacity;
    if (n < 2)
        throw illegalParameterValue("must have at least 2 objects");
    int *objectSize = new int[n+1];

    for (int i = 1; i <= n; i++)
    {
   
        cout << "Enter space requirement of object "
             << i << endl;
        cin >> objectSize[i];
        if (objectSize[i] > binCapacity)
            throw illegalParameterValue("Object too large to fit in a bin");
    }
    firstFitPack(objectSize, n, binCapacity);
    delete [] objectSize;
    return 0;
}

MaxmumLoserTree.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最大输者树——模板类
*/

#ifndef _31LOSERTREE_MINIMUMLOSERTREE_H
#define _31LOSERTREE_MINIMUMLOSERTREE_H
#include<iostream>
#include "loserTree.h"
#include "myExceptions.h"
using namespace std;

template<class T>
class MaxmumLoserTree : public loserTree<T> {
   
public:
    /*构造函数*/
    explicit MaxmumLoserTree(T *thePlayer = nullptr, int theNumberOfPlayers = 0) {
   
        tree = nullptr;
        advance = nullptr;
        initialize(thePlayer, theNumberOfPlayers);
    }

    /*析构函数*/
    ~MaxmumLoserTree() {
   
        delete[] tree;
        delete[] advance;
    }

    void initialize(T *thePlayer, int theNumberOfPlayers);//初始化
    [[nodiscard]] int getTheWinner() const {
    return tree[0]; };//输出当前的赢者
    [[nodiscard]] int getTheWinner(int i) const // 返回节点i的胜者的index
    {
   return (i < numberOfPlayers) ? advance[i] : 0;}
    void rePlay(int thePlayer);//重构
    void output() const;
private:
    int numberOfPlayers{
   };
    int *tree;// 记录内部结点,tree[0]是最终的赢者下标,不使用二叉树结点,因为父子关系都是通过计算得出
    int *advance;// 记录比赛晋级的成员
    T *player;//参与比赛的元素
    int lowExt{
   };//最底层外部结点的个数,2*(n-s)
    int offset{
   };//2*s-1
    void play(int, int, int);

    int winner(int x, int y) {
    return player[x] >= player[y] ? x : y; };//返回更大的元素下标
    int loser(int x, int y) {
    return player[x] >= player[y] ? y : x; };//返回更小的元素下标
};

template<class T>
void MaxmumLoserTree<T>::initialize(T *thePlayer, int theNumberOfPlayers) {
   
    int n = theNumberOfPlayers;
    if (n < 2) {
   
        throw illegalParameterValue("must have at least 2 players");
    }
    player = thePlayer;
    numberOfPlayers = n;
    // 删除原来初始化的内存空间,初始化新的内存空间
    delete[] tree;
    delete[] advance;
    tree = new int[n + 1];
    advance = new int[n + 1];
    // 计算s
    int s;
    for (s = 1; 2 * s <= n - 1; s += s);//s=2^log(n-1)-1(常数优化速度更快),s是最底层最左端的内部结点

    lowExt = 2 * (n - s);
    offset = 2 * s - 1;

    for (int i = 2; i <= lowExt; i += 2)//最下面一层开始比赛
        play((i + offset) / 2, i - 1, i);//父结点计算公式第一条

    int temp = 0;
    if (n % 2 == 1) {
   //如果有奇数个结点,一定会存在特殊情况,需要内部节点和外部节点的比赛
        play(n / 2, advance[n - 1], lowExt + 1);
        temp = lowExt + 3;
    } else temp = lowExt + 2;//偶数个结点,直接处理次下层

    for (int i = temp; i <= n; i += 2)//经过这个循环,所有的外部结点都处理完毕
        play((i - lowExt + n - 1) / 2, i - 1, i);

    tree[0] = advance[1];//tree[0]是最终的赢者,也就是决赛的赢者

}

template<class T>
void MaxmumLoserTree<T>::play(int p, int leftChild, int rightChild) {
   
    // tree结点存储相对较大的值,也就是这场比赛的输者
    tree[p] = loser(leftChild, rightChild);
    cout << "tree" << p << " : " << leftChild << " : " << rightChild << endl;
    // advance结点存储相对较小的值,也就是这场比赛的晋级者
    advance[p] = winner(leftChild, rightChild);
    cout << "advance" << p << " : " << leftChild << " : " << rightChild << endl;
    // 如果p是右孩子
    while (p % 2 == 1 && p > 1) {
   
        tree[p / 2] = loser(advance[p - 1], advance[p]);
        advance[p / 2] = winner(advance[p - 1], advance[p]);
        p /= 2;//向上搜索
    }
}

template<class T>
void MaxmumLoserTree<T>::rePlay(int thePlayer) {
   
    int n = numberOfPlayers;
    if (thePlayer <= 0 || thePlayer > n) {
   
        throw illegalParameterValue("Player index is illegal");
    }

    int matchNode,//将要比赛的场次
    leftChild,//比赛结点的左孩子
    rightChild;//比赛结点的右孩子

    if (thePlayer <= lowExt) {
   //如果要比赛的结点在最下层
        matchNode = (offset + thePlayer) / 2;
        leftChild = 2 * matchNode - offset;
        rightChild = leftChild + 1;
    } else {
   //要比赛的结点在次下层
        matchNode = (thePlayer - lowExt + n - 1) / 2;
        if (2 * matchNode == n - 1) {
   //特殊情况,比赛的一方是晋级
            leftChild = advance[2 * matchNode];
            rightChild = thePlayer;
        } else {
   
            leftChild = 2 * matchNode - n + 1 + lowExt;//这个操作是因为上面matchNode计算中/2取整了
            rightChild = leftChild + 1;
        }
    }
    //到目前位置,我们已经确定了要比赛的场次以及比赛的选手

    //下面进行比赛重构,也就是和赢者树最大的不同,分两种情况
    if (thePlayer == tree[0]) {
   //当你要重构的点是上一场比赛的赢家的话,过程比赢者树要简化,简化之后只需要和父亲比较,不需要和兄弟比较
        for (; matchNode >= 1; matchNode /= 2) {
   
            int oldLoserNode = tree[matchNode];//上一场比赛的输者
            tree[matchNode] = loser(oldLoserNode, thePlayer);
            advance[matchNode] = winner(oldLoserNode, thePlayer);
            thePlayer = advance[matchNode];
        }
    } else {
   //其他情况重构和赢者树相同
        tree[matchNode] = loser(leftChild, rightChild);
        advance[matchNode] = winner(leftChild, rightChild);
        if (matchNode == n - 1 && n % 2 == 1) {
   //特殊情况
            // 特殊在matchNode/2后,左孩子是内部节点,右孩子是外部节点
            matchNode /= 2;
            tree[matchNode] = loser(advance[n - 1], lowExt + 1);
            advance[matchNode] = winner(advance[n - 1], lowExt + 1);
        }
        matchNode /= 2;
        for (; matchNode >= 1; matchNode /= 2) {
   
            tree[matchNode] = loser(advance[matchNode * 2], advance[matchNode * 2 + 1]);
            advance[matchNode] = winner(advance[matchNode * 2], advance[matchNode * 2 + 1]);
        }
    }
    tree[0] = advance[1];//最终胜者
}

template<class T>
void MaxmumLoserTree<T>::output() const
{
   
    cout << "number of players = " << numberOfPlayers
         << " lowExt = " << lowExt
         << " offset = " << offset << endl;
    cout << "complete loser tree pointers are" << endl;
    for (int i = 1; i < numberOfPlayers; i++)
        cout << tree[i] << ' ';
    cout << endl;
}

#endif //_31LOSERTREE_MINIMUMLOSERTREE_H

loserTree.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最小输者树——虚基类
*/

#ifndef _31LOSERTREE_LOSERTREE_H
#define _31LOSERTREE_LOSERTREE_H

template<class T>
class loserTree {
   
public:
    virtual ~loserTree() {
   }
    virtual void initialize(T *thePlayer, int number) = 0;
    virtual int getTheWinner() const = 0;
    virtual void rePlay(int thePLayer) = 0;
};

#endif //_31LOSERTREE_LOSERTREE_H

myExceptions.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月18日16点28分
Last Version:			V1.0
Descriptions:			异常汇总
*/
#pragma once
#ifndef _MYEXCEPTIONS_H_
#define _MYEXCEPTIONS_H_
#include <string>
#include<iostream>
#include <utility>

using namespace std;

// illegal parameter value
class illegalParameterValue : public std::exception
{
   
public:
    explicit illegalParameterValue(string theMessage = "Illegal parameter value")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// illegal input data
class illegalInputData : public std::exception
{
   
public:
    explicit illegalInputData(string theMessage = "Illegal data input")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// illegal index
class illegalIndex : public std::exception
{
   
public:
    explicit illegalIndex(string theMessage = "Illegal index")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// matrix index out of bounds
class matrixIndexOutOfBounds : public std::exception
{
   
public:
    explicit matrixIndexOutOfBounds
            (string theMessage = "Matrix index out of bounds")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// matrix size mismatch
class matrixSizeMismatch : public std::exception
{
   
public:
    explicit matrixSizeMismatch(string theMessage =
    "The size of the two matrics doesn't match")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// stack is empty
class stackEmpty : public std::exception
{
   
public:
    explicit stackEmpty(string theMessage =
    "Invalid operation on empty stack")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// queue is empty
class queueEmpty : public std::exception
{
   
public:
    explicit queueEmpty(string theMessage =
    "Invalid operation on empty queue")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// hash table is full
class hashTableFull : public std::exception
{
   
public:
    explicit hashTableFull(string theMessage =
    "The hash table is full")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// edge weight undefined
class undefinedEdgeWeight : public std::exception
{
   
public:
    explicit undefinedEdgeWeight(string theMessage =
    "No edge weights defined")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};

// method undefined
class undefinedMethod : public std::exception
{
   
public:
    explicit undefinedMethod(string theMessage =
    "This method is undefined")
    {
   message = std::move(theMessage);}
    void outputMessage() {
   cout << message << endl;}
private:
    string message;
};
#endif

运行结果

"C:\Users\15495\Documents\Jasmine\prj\_Algorithm\Data Structures, Algorithms and Applications in C++\_32Box loading\cmake-build-debug\_32Box_loading_.exe"
Enter number of objects and bin capacity
4
7
Enter space requirement of object 1
3
Enter space requirement of object 2
5
Enter space requirement of object 3
2
Enter space requirement of object 4
4
number of players = 4 lowExt = 4 offset = 3
complete loser tree pointers are
3 2 4
Pack object 1 in bin 1
Pack object 2 in bin 2
Pack object 3 in bin 1
Pack object 4 in bin 3

Process finished with exit code 0

最近更新

  1. TCP协议是安全的吗?

    2023-12-21 13:24:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-21 13:24:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-21 13:24:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-21 13:24:03       18 阅读

热门阅读

  1. 记录 | 源码编译Arm CPU版FFmpeg

    2023-12-21 13:24:03       46 阅读
  2. Python爬虫山东重庆各地区天气预报

    2023-12-21 13:24:03       37 阅读
  3. 在国产GPU寒武纪MLU上快速上手Pytorch使用指南

    2023-12-21 13:24:03       49 阅读
  4. Ubuntu Docker图形界面实现

    2023-12-21 13:24:03       40 阅读
  5. C++高级:深拷贝与浅拷贝在嵌入式系统中的应用

    2023-12-21 13:24:03       42 阅读
  6. uni-app 微信小程序蓝牙模块的解耦封装-持续更新

    2023-12-21 13:24:03       33 阅读
  7. 速盾网络:网络安全守护者

    2023-12-21 13:24:03       46 阅读
  8. SpringBoot缓存注解@Cacheable使用姿势介绍

    2023-12-21 13:24:03       42 阅读
  9. 算法:从入门到变通

    2023-12-21 13:24:03       40 阅读
  10. 面试算法63:替换单词

    2023-12-21 13:24:03       40 阅读
  11. 在spring boot项目引入mybatis plus后的的案例实践

    2023-12-21 13:24:03       44 阅读