#include<cstdio> #include<iostream> using namespace std; int x[100]; template<class Type>class Loading{ friend Type MaxLoading(Type[], Type,int); public: void Backtrack(int i); int n; Type *w,c,cw,bestw; }; template<class Type> void Loading<Type>::Backtrack(int i) { if(i>n){ if(cw>bestw) bestw=cw; //cout<<i<<endl; return; } if(cw+w[i]<=c) { //cout<<w[i]<<endl; x[i]=1; cw+=w[i]; Backtrack(i+1); cw-=w[i]; //x[i]=0; //cout<<1; } Backtrack(i+1); } template<class Type> Type MaxLoading(Type w[],Type c,int n) { Loading <Type> X; X.w=w; for(int i=0;i<=3;++i) cout<<"w["<<i<<"]="<<X.w[i]<<endl;//测试输出 X.c=c; X.n=n; X.bestw=0;
X.cw=0; X.Backtrack(1); //cout<<X.bestw<<endl; return X.bestw; } int main() { int n=3; int w[]={0,1,3,9}; //for(int i=0;i<4;++i) //cout<<w[i]<<endl; int c=10; //Loading load; cout<<MaxLoading(w,c,n)<<endl; }
回溯法0-1背包问题
最新推荐文章于 2022-05-07 12:14:29 发布