其他分享
首页 > 其他分享> > 装载问题(回溯法)

装载问题(回溯法)

作者:互联网

 

 

#include<iostream>
using namespace std;


class Loading {
friend int MaxLoading(int* w, int c, int n, int* bestx);
private:
void Backtrack(int i);
int n;//集装箱数
int* x;//当前解
int* bestx;//当前最优解
int* w,//集装箱重量数组
c,//第一艘轮船的载重量
cw,//当前载重量
bestw,//当前最优载重量
r;//剩余集装箱载重量
};
void Loading::Backtrack(int i){
//搜索第i层结点
if (i > n) {
//到达叶结点
if (cw > bestw) {
for (auto j = 1; j <= n; j++)
bestx[j] = x[j];
bestw = cw;
}
return;
}
//搜索子树
r -= w[i];
if (cw + w[i] <= c) {
//搜索左子树
x[i] = 1;
cw += w[i];
Backtrack(i + 1);
cw -= w[i];
}
if (cw + r > bestw) {
//搜索右子树
x[i] = 0;
Backtrack(i + 1);
}
r += w[i];
}

int MaxLoading(int* w, int c, int n, int* bestx) {
//返回最优装载重量
Loading X;
//初始化X
X.x = new int[n + 1];
X.w = w;
X.c = c;
X.n = n;
X.bestx = bestx;
X.bestw = 0;
X.cw = 0;
//初始化r
X.r = 0;
for (auto i = 1; i <= n; i++)
X.r += w[i];
X.Backtrack(1);
delete[]X.x;
return X.bestw;
}
int main()
{
Loading X;
int* w = new int[6];
int c = 80;
int n = 5;
int* bestx = new int[6];
for (int i = 1; i <= 5; i++)
cin >> w[i];
cout<<MaxLoading(w, c, n, bestx)<<'\n';
for (int i = 1; i <= 5; i++) {
cout << bestx[i] << " ";
}

}
/*
10 20 30 40 50
*/

标签:问题,Loading,Backtrack,int,bestw,装载,bestx,回溯,cw
来源: https://www.cnblogs.com/msboke/p/14727106.html