AgPro

导航

0-1背包问题-动态规划

#include <iostream>
using namespace std;

//const int MAX_SIZE = 100;
//int n;		// 物品种类
//int c;		// 背包重量限制
//int w[MAX_SIZE];//weight
//int v[MAX_SIZE];//capacity
//int x[MAX_SIZE];//falg
//int m[MAX_SIZE][MAX_SIZE];

////也可以采用如下结构体方式
//typedef struct body 
//{     
//	char name[20];     
//	int weight;     
//	int value; 
//}bag;
//bag sack[N]= {{"A", 4, 5},{"B", 3, 2},{"C", 2, 1}};

int main()
{
	int n = 3;
	int c = 6;
	int w[3] = {4,3,2}; 
	int v[3] = {5,2,1};	
	int x[3];
	int m[3][6+1];
	int i,j;

	//1.Kanpsack
	//if j<wi:       m(i,j)=m(i+1,j)
	//if j>=wi, 就只要做出选择wi和不选择wi情况下,哪种使背包的总值更大:m(i,j)=max{ m(i+1,j),m(i+1,j-wi)+vi}
	//initial	m(n-1,j)=0       (0<=j<wn)  
	//		m(n-1,j)=v[n-1]  (j >= wn)	 
	//result        m(n-1,c)
	for ( j=0; j<=c; j++ )
	{
		if ( j < w[n-1] )
			m[n-1][j] = 0;			
		else
			m[n-1][j] = v[n-1];
	}
	for ( i=n-2; i>=0; i-- )
	{
		for ( j=0; j<=c; j++ )
		{	
			if ( j < w[i] )				
				m[i][j] = m[i+1][j];//m(i,j)=m(i+1,j)
			else				
				m[i][j] = max( m[i+1][j], m[i+1][j-w[i]]+v[i] );//m(i,j)=max{ m(i+1,j),m(i+1,j-wi)+vi}
		}  
	}  
	cout << "TotolValue: ";  
	cout << m[0][c] << endl;   

	//2.Traceback
	int captmp = c;
	for ( i=0; i<=n-2; i++ )
	{
		if ( m[i][captmp] == m[i+1][captmp] )
		{
			x[i] = 0;
		}
		else
		{
			x[i] = 1;
			captmp -= w[i];
		}
	}
	x[n-1] = (m[n-1][c]) ? 1 : 0;
	cout << "Knapsack Array: ";
	for ( i=0; i<n; i++ )
		cout << x[i] << " ";
	cout << endl;

	return 0; 
}

posted on 2010-06-12 15:01  AgPro  阅读(267)  评论(0编辑  收藏  举报