装载问题实质: 装载问题是一个子集选取问题,因此其解空间树是一颗子集树。
这里实现优先队列式分支限界法。
如果你在用优先队列时用less关键字,发现生成的并不是优先队列 参考https://blog.csdn.net/m0_38015368/article/details/80461938
#include <bits/stdc++.h>
using namespace std;
class MaxHeapQNode
{
public:
MaxHeapQNode *parent;
int lchild;
int weight;
int lev;
};
struct cmp
{
bool operator()(MaxHeapQNode *&a, MaxHeapQNode *&b) const
{
return a->weight < b->weight;
}
};
int n;
int c;
int bestw;
int w[100];
int bestx[100];
void InPut()
{
scanf("%d %d", &n, &c);
for(int i = 1; i <= n; ++i)
scanf("%d", &w[i]);
}
void AddAliveNode(priority_queue<MaxHeapQNode *, vector<MaxHeapQNode *>, cmp> &q, MaxHeapQNode *E, int wt, int i, int ch)
{
MaxHeapQNode *p = new MaxHeapQNode;
p->parent = E;
p->lchild = ch;
p->weight = wt;
p->lev = i + 1;
q.push(p);
}
void MaxLoading()
{
priority_queue<MaxHeapQNode *, vector<MaxHeapQNode *>, cmp > q; // 大顶堆
//定义剩余重量数组r
int r[n + 1];
r[n] = 0;
for(int j = n - 1; j > 0; --j)
r[j] = r[j + 1] + w[j + 1];
int i = 1;
MaxHeapQNode *E;
int Ew = 0;
while(i != n + 1)
{
if(Ew + w[i] <= c)
{
AddAliveNode(q, E, Ew + w[i] + r[i], i, 1);
}
AddAliveNode(q, E, Ew + r[i], i, 0);
//取下一节点
E = q.top();
q.pop();
i = E->lev;
Ew = E->weight - r[i - 1];
}
bestw = Ew;
for(int j = n; j > 0; --j)
{
bestx[j] = E->lchild;
E = E->parent;
}
}
void OutPut()
{
printf("最优装载量为 %d\n", bestw);
printf("装载的物品为 \n");
for(int i = 1; i <= n; ++i)
if(bestx[i] == 1)
printf("%d ", i);
}
int main()
{
InPut();
MaxLoading();
OutPut();
}
测试样例:
输入:
(多解,输出其中一个)
4 60
10
40
50
20
输出
最优装载量为 60
装载的物品为
1 3
运行截图