递归:背包问题[M, N]

//背包问题[M, N]
#include<iostream>
using namespace std;
int M, N, solution;
int *pOut;

void Comput(int m, int n)
{
	if( m < 1 || n < 1 || ( n == 1 && m != 1 ))
		return;
	//if remaining space = bag size
	if( m==n )
	{
		pOut[n] = 1;
		cout<<"Solution "<<++solution<<": ";
		for ( int i = 1; i <= N; i++ )
		{
			if( pOut[i] )
				cout<<i<<" ";
		}
		cout<<endl;
		pOut[n] = 0;//reset bag status
	}

	Comput( m, n-1);//not use bag n

	pOut[n] = 1; //mark current bag(used) = 1
	Comput(m - n, n - 1);//use bag [n]
	pOut[n] = 0;
}
void main()
{
	printf("Input M(total weights), N(number of bags): ");
	scanf("%d %d", &M, &N);
	if( M < N )
		N = M;
	pOut = new int[N+1];
	memset(pOut, 0, (N+1)*sizeof(int) );

	Comput(M, N);
	delete []pOut;
	cout<<"Total solutions: "<<solution<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include <iostream.h> #include<iomanip.h> #include<string.h> int min(int w,int c) {int temp; if (w<c) temp=w; else temp=c; return temp; } int max(int w,int c) { int temp; if (w>c) temp=w; else temp=c; return temp; } void knapsack(int v[],int w[],int c,int n,int**m) //求最优值 { int jmax=min(w[n]-1,c); for(int j=0;j<=jmax;j++) m[n][j]=0; for(int jj=w[n];jj<=c;jj++) m[n][jj]=v[n]; for(int i=n-1;i>1;i--){ //递归部分 jmax=min(w[i]-1,c); for(int j=0;j<=jmax;j++) m[i][j]=m[i+1][j]; for(int jj=w[i];jj<=c;jj++) m[i][jj]=max(m[i+1][jj],m[i+1][jj-w[i]]+v[i]); } m[1][c]=m[2][c]; if(c>=w[1]) m[1][c]=max(m[1][c],m[2][c-w[1]]+v[1]); cout<<"最优值:"<<m[1][c]<<endl; for(int l=2;l<=n;l++) for(int j=0;j<=c;j++) { cout<<m[l][j]<<setw(c-1); } cout<<endl; cout<<"*******************************************"<<endl; } int traceback(int **m,int w[],int c,int n,int x[]) //回代,求最优解 { cout<<"得到的一组最优解如下:"<<endl; for(int i=1;i<n;i++) if(m[i][c]==m[i+1][c]) x[i]=0; else {x[i]=1; c-=w[i];} x[n]=(m[n][c])?1:0; for(int y=1;y<=n;y++) { cout<<setw(5)<<x[y]; } return x[n]; } void main() { int n,c; int **m; cout<<"欢迎使用0-1背包问题程序"<<endl; cout<<"请输入物品个数和重量上限:"; cin>>n>>c; int *v=new int[n+1]; cout<<"Pls input the property (v[i]):"<<endl; for(int i=1;i<=n;i++) cin>>v[i]; int *w=new int[n+1]; cout<<"Pls input the weight (w[i]):"<<endl; for(int j=1;j<=n;j++) cin>>w[j]; int *x=new int[n+1]; m=new int*[n+1]; //动态的分配二维数组 for(int p=0;p<n+1;p++) { m[p]=new int[c+1]; } knapsack(v,w,c,n,m); traceback(m,w,c,n,x); }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值