《数据结构、算法与应用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);
    }
}

有重复值的二叉搜索树实现最优适配法

在实现最优匹配法时,搜索树的每个元素代表一个正在使用且剩余容量不为0的箱子。每个箱子的剩余容量作为节点的关键字,每个箱子的名称作为节点的值。

在有重复值的二叉搜索树模板类中实现findGE()共有成员函数,该函数旨在寻找最匹配的箱子,即剩余容量大于等于theKey又是剩余容量最小的箱子bestBin。从根节点cur开始搜索,当cur->element.first >= theKey,记录&cur->element到bestBin,再移动到左孩子去找;否则,移动到右孩子去找;直到cur为空。
代码:

/*  查找元素,目的是解决箱子装载问题的最有匹配方法,将element.first作为箱子的容量,element.second作为箱子的名称
 *  输入:theKey表示需要查找元素的键值
 *  输出:返回值是剩余容量即大于等于theKey又是最小的箱子的element的地址
 *  时间复杂度:O(logn),n表示节点个数
 */
template<class K, class E>
pair<K, E>* dBinarySearchTree<K,E>::findGE(const K theKey) const{
    // 返回一个元素的指针,这个元素的关键字是不小于theKey的最小关键字
    // 如果这样的元素不存在,返回NULL
    binaryTreeNode<pair<K, E>> * cur = root;
    // 目前找到的元素,其关键字是不小于theKey的最小关键字
    pair<K, E> * bestBin = nullptr;
    // 对树搜索
    while(cur != nullptr){
        // cur是一个候选者吗
        if(cur->element.first >= theKey) // 是比bestBin更好的候选者
        {
            bestBin = &cur->element;
            cur = cur->leftChild;// 再往左子树去找
        }
        else // 不是
            cur = cur->rightChild;// 再往右子树去找
    }
    return bestBin;
}

使用带有重复值的二叉搜索树实现最优适配法的时间复杂度为O(nlogn),n表示物品个数。定义一个dBinarySearchTree对象theTree,对于没件物品,寻找最合适的箱子装箱,调用theTree.findGE(objectSize[i])寻找最合适的箱子,当返回值为空时,说明没有足够大的箱子,启用一个新箱子;反之,存储最合适的箱子,删除theTree树中最合适的箱子。装箱之后,更新最合适箱子的容量,更新好后当容量大于0,将该箱子重新插入theTree中。直到所有物品都找到合适的箱子。

代码:

/*
 * 最优适配算法的实现
 * objectSize数组存储物体的重量,objectSize[i]表示物体i的重量
 * numberOfObjects存储物体的数量
 * binCapacity存储初始时箱子的容量
 * 时间复杂度:O(logn)
 */
void bestFitPack(int *objectSize, int numberOfObjects, int binCapacity) {
    // 输出容量为binCapacity的最优箱子匹配.
    // objectSize[1:numberOfObjects]表示物品大小
    int n = numberOfObjects;
    int binsUsed = 0; // 表示使用了多少个箱子,方便给箱子取名字
    // 箱子容量树 pair<K, E>.first表示箱子的容量,pair<K, E>.second表示箱子的名称
    dBinarySearchTree<int, int> theTree;
    pair<int, int> theBin;

    // 将物品逐个装箱
    for (int i = 1; i <= n; i++) {
        // 将物品i装箱
        // 寻找最合适的箱子
        pair<int, int> *bestBin = theTree.findGE(objectSize[i]);
        if (bestBin == nullptr) {// 没有足够大的箱子,启用一个新箱子
            theBin.first = binCapacity;
            theBin.second = ++binsUsed;
        } else {// 从树theTree中删除最匹配的箱子
            theBin = *bestBin;
            theTree.erase(bestBin->first);
        }

        cout << "Pack object " << i << " in bin "
             << theBin.second << endl;

        // 将箱子插到树中,除非箱子已满
        theBin.first -= objectSize[i];
        if (theBin.first > 0)
            theTree.insert(theBin);
    }
}

代码

main.cpp

// first fit bin packing

#include <iostream>
#include "MaxmumLoserTree.h"
#include "dBinarySearchTree.h"

using namespace std;

/*最大输者树的测试*/
void MaxmumLoserTreeTest() {
    cout << "*************************MaxmumLoserTreeTest() begin*******************************" << endl;
    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];
    }

    auto *w = new MaxmumLoserTree<int>(thePlayer, n);
    cout << "The loser tree is" << endl;
    w->output();
    cout << "*************************MaxmumLoserTreeTest() end*******************************" << endl;
}

// 最先适配算法的实现
/*
 * 最先适配算法的实现
 * objectSize数组存储物体的重量,objectSize[i]表示物体i的重量
 * numberOfObjects存储物体的数量
 * binCapacity存储初始时箱子的容量
 * 时间复杂度:O(nlogn)
 */
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);
    }
}

/*最先适配算法的测试*/
void firstFitPackTest(){
    cout << "*************************firstFitPackTest() begin*******************************" << endl;
    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;
    cout << "*************************firstFitPackTest() end*******************************" << endl;
}
/*
 * 最优适配算法的实现
 * objectSize数组存储物体的重量,objectSize[i]表示物体i的重量
 * numberOfObjects存储物体的数量
 * binCapacity存储初始时箱子的容量
 * 时间复杂度:O(logn)
 */
void bestFitPack(int *objectSize, int numberOfObjects, int binCapacity) {
    // 输出容量为binCapacity的最优箱子匹配.
    // objectSize[1:numberOfObjects]表示物品大小
    int n = numberOfObjects;
    int binsUsed = 0; // 表示使用了多少个箱子,方便给箱子取名字
    // 箱子容量树 pair<K, E>.first表示箱子的容量,pair<K, E>.second表示箱子的名称
    dBinarySearchTree<int, int> theTree;
    pair<int, int> theBin;

    // 将物品逐个装箱
    for (int i = 1; i <= n; i++) {
        // 将物品i装箱
        // 寻找最合适的箱子
        pair<int, int> *bestBin = theTree.findGE(objectSize[i]);
        if (bestBin == nullptr) {// 没有足够大的箱子,启用一个新箱子
            theBin.first = binCapacity;
            theBin.second = ++binsUsed;
        } else {// 从树theTree中删除最匹配的箱子
            theBin = *bestBin;
            theTree.erase(bestBin->first);
        }

        cout << "Pack object " << i << " in bin "
             << theBin.second << endl;

        // 将箱子插到树中,除非箱子已满
        theBin.first -= objectSize[i];
        if (theBin.first > 0)
            theTree.insert(theBin);
    }
}

/*最优适配算法测试*/
void bestFitPackTest(){
    cout << "*************************bestFitPackTest() begin*******************************" << endl;
    cout << "Enter number of objects and bin capacity" << endl;
    int numberOfObjects, binCapacity;
    cin >> numberOfObjects >> binCapacity;
    if (numberOfObjects < 2)
    {
        cout << "Too few objects" << endl;
        exit(1);
    }

    // 输入物体大小objectSize[1:numberOfObjects]
    int *objectSize = new int [numberOfObjects + 1];
    for (int i = 1; i <= numberOfObjects; i++)
    {
        cout << "Enter space requirement of object " << i << endl;
        cin >> objectSize[i];
        if (objectSize[i] > binCapacity)
        {
            cout << "Object too large to fit in a bin" << endl;
            exit(1);
        }
    }

    // 输出分装物品到箱子的结果
    bestFitPack(objectSize, numberOfObjects, binCapacity);
    delete [] objectSize;
    cout << "*************************bestFitPackTest() end*******************************" << endl;
}


// test program
int main() {
    /*最先适配算法测试*/
    firstFitPackTest();
    /*最优适配算法测试*/
    bestFitPackTest();
    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

dBinarySearchTree.h

/*
Project name :			_33Search_tree
Last modified Date:		2023年12月21日11点13分
Last Version:			V1.0
Descriptions:			二叉搜索树——带有相同关键字的二叉搜索树模板类
*/

#ifndef _33SEARCH_TREE_DBINARYSEARCHTREE_H
#define _33SEARCH_TREE_DBINARYSEARCHTREE_H
#include "bsTree.h"
#include "binaryTreeNode.h"
using namespace std;

template<class K, class E>
class dBinarySearchTree : public bsTree<K,E>
{
public:
    dBinarySearchTree(){
        root = nullptr;
        treeSize = 0;
    }
    // 字典相关的方法
    bool empty() const {return treeSize == 0;}
    int size() const {return treeSize;}
    pair<K, E>* find(const K theKey) const;
    pair<K, E>* findGE(const K theKey) const;
    void insert(const pair<K, E> thePair);
    void erase(const K theKey);
    /*中序遍历二叉树,使用函数指针的目的是是的本函数可以实现多种目的*/
    void inOrder(void(*theVisit)(binaryTreeNode<pair<K, E>>*))
    {
        visit = theVisit;
        /*是因为递归,所以才要这样的*/
        inOrder(root);/*这里调用的是静态成员函数inOrder()*/
    }
    /*中序遍历---输出endl*/
    void inOrderOutput() { inOrder(output); cout << endl; }

    // additional method of bsTree
    void ascend() {inOrderOutput();}
private:
    binaryTreeNode<pair<K, E>>* root;//指向根的指针
    int treeSize;//树的结点个数
    static void (*visit)(binaryTreeNode<pair<K, E>>*);//是一个函数指针,返回值为void 函数参数为binaryTreeNode<pair<K, E>>*
    static void output(binaryTreeNode<pair<K, E>>* t) { cout << t->element << " "; }
    static void inOrder(binaryTreeNode<pair<K, E>>* t);
};

/*私有静态成员初始化*/
/*这里是静态函数指针成员的初始化,不初始化会引发LINK错误*/
template<class K, class E>
void (*dBinarySearchTree<K,E>::visit)(binaryTreeNode<pair<K, E>>*) = 0;      // visit function

/*中序遍历 递归*/
template<class K, class E>
void dBinarySearchTree<K,E>::inOrder(binaryTreeNode<pair<K, E>>* t)
{
    if (t != nullptr)
    {
        inOrder(t->leftChild);/*中序遍历左子树*/
        visit(t);/*访问树根*/
        inOrder(t->rightChild);/*中序遍历右子树*/
    }
}

/*  查找元素
 *  输入:theKey表示需要查找元素的键值
 *  输出:键值为theKey的节点的pair地址
 *  时间复杂度:O(logn),n表示节点个数
 */
template<class K, class E>
pair<K, E>* dBinarySearchTree<K,E>::find(K theKey) const
{
    // 返回值是匹配数对的指针
    // 如果没有匹配的数对,返回值为nullptr
    // p从根节点开始搜索,寻找关键字等于theKey的一个元素
    binaryTreeNode<pair<K, E> > *p = root;
    while (p != nullptr)
        // 检查元素 p->element
        if (theKey < p->element.first)
            p = p->leftChild;
        else
        if (theKey > p->element.first)
            p = p->rightChild;
        else // 找到匹配的元素
            return &p->element;

    // 没找到匹配的元素
    return nullptr;
}

/*  查找元素,目的是解决箱子装载问题的最有匹配方法,将element.first作为箱子的容量,element.second作为箱子的名称
 *  输入:theKey表示需要查找元素的键值
 *  输出:返回值是剩余容量即大于等于theKey又是最小的箱子的element的地址
 *  时间复杂度:O(logn),n表示节点个数
 */
template<class K, class E>
pair<K, E>* dBinarySearchTree<K,E>::findGE(const K theKey) const{
    // 返回一个元素的指针,这个元素的关键字是不小于theKey的最小关键字
    // 如果这样的元素不存在,返回NULL
    binaryTreeNode<pair<K, E>> * cur = root;
    // 目前找到的元素,其关键字是不小于theKey的最小关键字
    pair<K, E> * bestBin = nullptr;
    // 对树搜索
    while(cur != nullptr){
        // cur是一个候选者吗
        if(cur->element.first >= theKey) // 是比bestBin更好的候选者
        {
            bestBin = &cur->element;
            cur = cur->leftChild;// 再往左子树去找
        }
        else // 不是
            cur = cur->rightChild;// 再往右子树去找
    }
    return bestBin;
}

/*
 *  插入元素
 *  输入:const pair<K, E> thePair表示需要插入的键值对
 *  输出:void
 *  时间复杂度:O(logn),表示节点个数
 */
template<class K, class E>
void dBinarySearchTree<K,E>::insert(const pair<K, E> thePair)
{
    // 插入thePair. 如果该键值存在则覆盖元素
    // 寻找插入位置
    binaryTreeNode<pair<K, E> > *p = root,
            *pp = nullptr;
    while (p != nullptr)
    {// 检查元素 p->element
        pp = p;
        // 如果当前键值小于等于p的键值,则移到p的左孩子
        if (thePair.first <= p->element.first)
            p = p->leftChild;
        else// 如果当前键值大于p的键值,则移到p的右孩子
            p = p->rightChild;
    }

    // 为thePair建立一个节点,然后与pp链接,此时pp是叶子节点
    auto *newNode = new binaryTreeNode<pair<K, E> > (thePair);
    if (root != nullptr) // 树非空
        // 如果thePair的键值小于pp的键值,则将thePair作为pp的左孩子,反之将其作为右孩子
        if (thePair.first < pp->element.first)
            pp->leftChild = newNode;
        else
            pp->rightChild = newNode;
    else// 树空
        root = newNode; // 直接将thePair节点作为根节点
    treeSize++;
}
/*
 *  删除元素
 *  输入:const K theKey表示需要删除元素的键值
 *  输出:void
 *  时间复杂度:O(logn),n表示节点个数
 */
template<class K, class E>
void dBinarySearchTree<K,E>::erase(const K theKey)
{
    // 删除关键字等于theKey的数对
    // 查找关键字为theKey的节点
    binaryTreeNode<pair<K, E> > *p = root,
            *pp = nullptr;
    while (p != nullptr && p->element.first != theKey)
    {
        pp = p;
        if (theKey < p->element.first)
            p = p->leftChild;
        else
            p = p->rightChild;
    }
    if (p == nullptr)
        return; // 不存在与关键字theKey匹配的数对

    // 重新组织树结构
    // 当p有两个孩子时的处理
    if (p->leftChild != nullptr && p->rightChild != nullptr)
    {
        // 两个孩子
        // 在P的左子树中寻找最大元素
        binaryTreeNode<pair<K, E> > *s = p->leftChild,
                *ps = p;  // s的父节点
        while (s->rightChild != nullptr)
        {// 移动到更大的pair
            ps = s;
            s = s->rightChild;// 右孩子比较大
        }

        // 将最大元素s移到p
        // p->element = s->element 的键值是 const
        // 当最大值就是p的左孩子时,new的元素不能直接指向p的左孩子,而要指向p的左孩子的左孩子(此时p的左孩子没有右孩子),因为到时候s会被delete掉,这个问题在后面的p至多有一个孩子那里解决的
        binaryTreeNode<pair<K, E> >* q = nullptr;
        q = new binaryTreeNode<pair<K, E> >(s->element, p->leftChild, p->rightChild);
        // pp是p的父节点
        // 如果p没有父节点
        if (pp == nullptr)
            root = q;
        else if (p == pp->leftChild)// 如果p是pp的左孩子
            pp->leftChild = q;
        else// 如果p是pp的右孩子
            pp->rightChild = q;
        // 如果s的父节点就是p,说明p节点的左子树只有左子树没有右子树
        // 那么删除p后pp就是其父节点
        if (ps == p) pp = q;
        else pp = ps;// 反之ps是其父节点
        delete p;
        p = s;
    }

    // p至多只有一个孩子
    // 把孩子的指针存放到c
    binaryTreeNode<pair<K, E> > *c;
    if (p->leftChild != nullptr)
        c = p->leftChild;
    else
        c = p->rightChild;

    // 删除p
    if (p == root)
        root = c;
    else
    {// p是pp的左孩子还是右孩子
        if (p == pp->leftChild)
            pp->leftChild = c;
        else pp->rightChild = c;
    }
    treeSize--;
    delete p;
}
// overload << for pair
template <class K, class E>
ostream& operator<<(ostream& out, const pair<K, E>& x)
{out << x.first << ":" << x.second; return out;}
#endif //_33SEARCH_TREE_DBINARYSEARCHTREE_H

binaryTreeNode.h

/*
Project name :			allAlgorithmsTest
Last modified Date:		2022年8月27日09点44分
Last Version:			V1.0
Descriptions:			二叉树的结点结构体
*/
#pragma once
#ifndef _BINARYTREENODE_H_
#define _BINARYTREENODE_H_
template <class T>
struct binaryTreeNode
{
    T element;
    binaryTreeNode<T> *leftChild,   // left subtree
    *rightChild;  // right subtree

    binaryTreeNode() {leftChild = rightChild = nullptr;}
    explicit binaryTreeNode(const T& theElement):element(theElement)
    {
        leftChild = rightChild = nullptr;
    }
    binaryTreeNode(const T& theElement,
                   binaryTreeNode *theLeftChild,
                   binaryTreeNode *theRightChild)
            :element(theElement)
    {
        leftChild = theLeftChild;
        rightChild = theRightChild;
    }
};

#endif

bsTree.h

/*
Project name :			_33Search_tree
Last modified Date:		2023年12月21日11点13分
Last Version:			V1.0
Descriptions:			二叉搜索树——虚基类
*/

#ifndef _33SEARCH_TREE_BSTREE_H
#define _33SEARCH_TREE_BSTREE_H
#include "dictionary.h"

using namespace std;

template<class K, class E>
class bsTree : public dictionary<K,E>
{
public:
    virtual void ascend() = 0;
    // 按关键字升序输出
};
#endif //_33SEARCH_TREE_BSTREE_H

dictionary.h

/*
Project name :			_33Search_tree
Last modified Date:		2023年12月21日11点13分
Last Version:			V1.0
Descriptions:			字典虚基类
*/

#ifndef _33SEARCH_TREE_DICTIONARY_H
#define _33SEARCH_TREE_DICTIONARY_H
#include <iostream>
#include <utility>

using namespace std;

template<class K, class E>
class dictionary
{
public:
    virtual ~dictionary() = default;
    [[nodiscard]] virtual bool empty() const = 0;
    // 如果字典为空则返回true,反之返回false
    [[nodiscard]] virtual int size() const = 0;
    // 返回字典中有多少个pair
    virtual pair<K, E>* find(const K) const = 0;
    // 根据键值返回pair的指针
    virtual void erase(const K) = 0;
    // 根据键值移除pair元素
    virtual void insert(const pair<K, E>) = 0;
    // 插入一个(key, value)pair到字典中
};
#endif //_33SEARCH_TREE_DICTIONARY_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"
*************************firstFitPackTest() begin*******************************
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
*************************firstFitPackTest() end*******************************
*************************bestFitPackTest() begin*******************************
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
Pack object 1 in bin 1
Pack object 2 in bin 2
Pack object 3 in bin 2
Pack object 4 in bin 1
*************************bestFitPackTest() end*******************************

Process finished with exit code 0

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值