回溯法解装载问题

王晓东老师算法设计与分析书当中关于回溯一章有一个实例是装载问题。在研究此算法的过程中也试着实现了一下此问题,当用某种特定类型的时候实现是没有问题的,但是一旦使用了类模板就会出错,提示说不能访问类中的私有变量。自己也完全抄过书中的代码,一样提示出错。很不解。

专门搜索了一下模板与友元,终于找到了答案,原来在类模板中声明模板函数为友元函数在C++ primer当中有专门一节的讲解。读完后,更改代码正确运行。不懂的读者也可以去读一读。关键的一点:

template<class T>void p(void);

template<class T>

class t

{

friend void p<T>(void);

};

template<class T>

void p(void){}


上述代码中,类T是模板类,函数P是模板函数,如果要把p声明为类t的友元,则必须在类之前声明函数原型,并且在类当中一定要声明这是一个模板函数。


回溯问题的代码:

#include<iostream>
using namespace std;

template<class Type>
Type MaxLoading(Type w[],Type c,int n);


template<class Type>
class loading
{


friend Type MaxLoading<Type>(Type w[], Type c,int n);
private:
Type result;
Type bestw;


int n;
int c;
Type *w;
void Backtrack(int i);
};


template<class Type>
void loading<Type>::Backtrack(int i)
{
if(i>n)
{
if(result>bestw)
bestw=result;
return;
}

if(result+w[i] <=c)
{
result+=w[i];
Backtrack(i+1);
result-=w[i];
}

Backtrack(i+1);
}


template<class Type>
Type MaxLoading(Type w[],Type c,int n)
{
loading<Type> l;
l.result=0;
l.bestw=0;


l.n=n;
l.c=c;
l.w=w;
l.Backtrack(1);
return l.bestw;
}

int main()
{
int a[6]={0,3,4,2,6,10};
int c=10;
int bb=MaxLoading<int>(a,c,5);
cout<<bb;
system("pause");
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值