[算法]分支界限法解决装载问题

#include 

using namespace std;

typedef struct QNode {
    QNode *parent;// 父节点指针
    bool lChild;// 子节点
    int weight;// 货物重量
} QNode;

int n;// 货物数量
int maxLoadingWt;// 最大装载重量
int bestWt;// 最优装载量
int wt[100];// 货物重量集合
int bestCh[100];// 最优装载选择集合

void EnQueue(queue<QNode *> &q, int i, int ch, int weight, QNode *E, QNode *&bestE) {
    if (i == n) {// 达到叶子节点
        if (weight == bestWt) {// 找到最优解
            bestE = E;
            bestCh[i] = ch;
            return;
        }
    }
    QNode *tmp;
    tmp = new QNode;
    tmp->weight = weight;
    tmp->lChild = ch;
    tmp->parent = E;
    q.push(tmp);
}


void Input() {
    cout << "Please input the number of goods and the maximum of loading:" << endl;
    cin >> n >> maxLoadingWt;
    cout << "The weight array is..." << endl;
    for (int i = 1; i <= n; ++i) {
        cin >> wt[i];
    }
}

void Output() {
    cout << "->>>>>>>>>>>>>>>>>>>>>>>>" << endl;
    cout << "The maximum of loading weight is:" << bestWt << endl
         << "The choice is:" << endl;
    for (int i = 1; i <= n; ++i) {
        if (bestCh[i])
            cout << i << " ";
    }

}

void MaxLoading() {
    queue<QNode *> q;
    q.push(0);// 分层标志
    int i = 1;// 选择第一个货物
    int r = 0;// 剩余货物重量
    int wtLoaded = 0;// 当前已装货物重量
    bestWt = 0;//当前最优解
    /*计算当前剩余货物重量 已预选定第一个货物*/
    for (int j = 2; j <= n; ++j)
        r += wt[j];
    QNode *E, *bestE;
    E = new QNode;
    E = 0;// 初始父节点指针指向根(0)

    while (true) {
        int wtPreLoaded;// 预装载后货物重量
        wtPreLoaded = wtLoaded + wt[i];
        if (wtPreLoaded <= maxLoadingWt) {
            if (wtPreLoaded > bestWt)
                bestWt = wtPreLoaded;
            EnQueue(q, i, 1, wtPreLoaded, E, bestE);
        }
        if (wtLoaded + r >= bestWt)
            EnQueue(q, i, 0, wtLoaded, E, bestE);
        E = q.front();
        q.pop();
        if (!E) {
            if (q.empty())
                break;
            q.push(0);
            E = q.front();
            q.pop();
            i++;
            r -= wt[i];
        }
        wtLoaded = E->weight;
    }
    for (int j = n - 1; j > 0; --j) {
        bestCh[j] = bestE->lChild;
        bestE = bestE->parent;
    }
}

int main() {
    Input();
    MaxLoading();
    Output();
    return 0;
}

你可能感兴趣的:(算法)