装载问题(回溯法)
类似01背包问题,可以用动态规划,但有时候使用回溯法会更加高效。
#include<iostream>
#include<iomanip>
#define GOODS_NUM 4
using namespace std;
template<class Type>
Type maxLoading(Type w[], Type c, int n, int bestx[]) {
int i = 1;
int* x = new int[n + 1];
Type bestw = 0,
cw = 0,
r = 0;
for (int i = 1; i <= n; i++) {
r += w[i];
}
while (true) {
while (i <= n && cw + w[i] <= c) {
r -= w[i];
cw += w[i];
x[i] = 1;
i++;
}
if (i > n) {
for (int j = 1; j <= n; j++) {
bestx[j] = x[j];
}
bestw = cw;
}
else {
r -= w[i];
x[i] = 0;
i++;
}
while (cw + r <= bestw) {
i--;
while (i > 0 && !x[i]) {
r += w[i];
i--;
}
if (i == 0) {
delete[] x;
return bestw;
}
x[i] = 0;
cw -= w[i];
i++;
}
}
}
int main() {
int w[GOODS_NUM+1] = { -1,10,30,40,20 },
c = 70,
* bestx = NULL,
bestw;
bestx = new int[GOODS_NUM + 1];
bestw = maxLoading(w, c, GOODS_NUM, bestx);
cout << "bestw:" << bestw << endl;
for (int i = 1; i <= GOODS_NUM; i++) {
cout << setw(3) << w[i];
}
cout << endl;
for (int i = 1; i <= GOODS_NUM; i++) {
cout << setw(3) << bestx[i];
}
delete[] bestx;
return 0;
}
|