回溯法:最大装载问题(使用递归,优化搜索的同时取得最佳路径)

// 16x3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include<iostream.h>

template<class T>
class Loading {
friend GetMaxLoading(T [], T, int, int []);
private:
void Compute(int i);
int n,
*x, // 当前取值
*bestx; // 目前的最佳方案
T *w, // 货箱重量数组
c, // 第一艘船的容量
cw, // 当前的装载重量
bestw, // 目前最优装载重量
r;
};

template<class T>
void Loading<T>::Compute(int i)
{
if (i > n) {
bestw = cw; // 与16x1有所不同,只要到移到了叶节点,就必定是最佳方案
for (int j = 1; j <= n; j++)
bestx[j] = x[j];
return;
}

r -= w[i];
if (cw + w[i] <= c) {
x[i] = 1; // 此时x=1
cw += w[i];
Compute(i+1);
cw -= w[i];
}
if (cw + r > bestw) {//
x[i] = 0; // 此时x=0
Compute(i+1);
}
r += w[i];
}

template<class T>
T GetMaxLoading(T w[], T c, int n, int bestx[])
{
Loading<T> 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;

X.r = 0;
for (int i = 1; i <= n; i++)
X.r += w[i];

X.Compute(1);
delete [] X.x;
return X.bestw;
}

void main(void)
{
int w[6] = {0, 2, 2, 6, 5, 4};
int x[6]; // 最佳取值路径
int n = 5;
int c = 10;
cout << "Value of max loading is" << endl;
cout << GetMaxLoading(w,c,n,x) << endl;
cout << "x values are" << endl;
for (int i=1; i<=n; i++)
cout << x[i] << ' ';
cout << endl;
}
posted @ 2012-02-10 03:46  findumars  Views(854)  Comments(0Edit  收藏  举报