4. 构造最优解
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 构造最优解
template <class Type>
class Loading
{
friend Type MaxLoading(Type[], Type, int, int[]); // 友元函数
private:
void Backtrack(int i); // 回溯函数
int n, // 集装箱数
*x, // 当前解
*bestx; // 当前最优解
Type *w, // 集装箱重量数组
c, // 第一艘轮船的在载重量
cw, // 当前载重量
bestw, // 当前最优装载重量
r; // 剩余集装箱重量
};
template <class Type>
void Loading<Type> ::Backtrack(int i){ // 定义成员函数,搜索第i层节点
if(i>n){ // 到达叶节点
if(cw>bestw){
for(int 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];
}
template <class Type>
Type MaxLoading(Type w[], Type c, int n, int bestx[]){ // 定义友元函数,返回最优载重量
Loading <Type> 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.Backtrack(1);
delete[] X.x;
return X.bestw;
}
int main(){
//--//定义变量--------------------
int i;
int n,c,m;
string fname;
cout<<"装载问题的数据文件名字(包括扩展名)"<<endl;
cout<<"数据内容包括: n, c, w"<<endl;
cin >> fname;
//fname="b.txt";
ifstream infile(fname.c_str(),ios::in);
if(!infile){
cerr<<" "<<endl;
exit(1);
}
infile>>n;
infile>>c;
int *w=new int[n+1];
for(i=1;i<n+1;i++)
infile>>w[i];
infile.close();
int *bestx=new int[n+1];
//--//调用函数--------------------
m=MaxLoading(w,c,n,bestx); // 求解问题
cout<<"集装箱数量: "<<n<<endl;
cout<<"集装箱重量: ";
for(i=1;i<n+1;i++)
cout<<w[i]<<" ";
cout<<endl;
cout<<"船的载重量: "<<c<<endl;
cout<<"最优载重量: "<<m<<endl;
cout<<"装载方案为: ";
for(i=1;i<n+1;i++)
cout<<bestx[i]<<" ";
cout<<endl;
//--//删除动态数组----------------
delete []w;
delete []bestx;
//--//暂停------------------------
cout<<endl;
system("pause");
return 0;
}
算法设计与分析,宋老师