2. 算法设计
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 算法设计
template <class Type>
class Loading
{
friend Type MaxLoading(Type[], Type, int); // 友元函数
private:
void Backtrack(int i); // 回溯函数
int n; // 集装箱数
Type *w, // 集装箱重量数组
c, // 第一艘轮船的在载重量
cw, // 当前载重量
bestw; // 当前最优装载重量
};
template <class Type>
void Loading<Type> ::Backtrack(int i){ // 定义成员函数,搜索第i层节点
if(i>n){ // 到达叶节点
if(cw>bestw)
bestw=cw;
return;
}
// 搜索子树
if(cw+w[i]<=c){ // x[i]=1
cw += w[i];
Backtrack(i+1);
cw -= w[i];
}
Backtrack(i+1); // x[i]=0
}
template <class Type>
Type MaxLoading(Type w[], Type c, int n){ // 定义友元函数,返回最优载重量
Loading <Type> X;
X.w = w;
X.c = c;
X.n = n;
X.bestw = 0;
X.cw = 0;
X.Backtrack(1);
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();
//--//调用函数--------------------
m=MaxLoading(w,c,n); // 求解问题
cout<<"集装箱数量: "<<n<<endl;
cout<<"集装箱重量: ";
for(i=1;i<n+1;i++)
cout<<w[i]<<" ";
cout<<endl;
cout<<"船的载重量: "<<c<<endl;
cout<<"最优载重量: "<<m<<endl;
//--//删除动态数组----------------
delete []w;
//--//暂停------------------------
cout<<endl;
system("pause");
return 0;
}
算法设计与分析,宋老师