回溯法解装载问题-4构造最优解

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;
}

算法设计与分析,宋老师

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值