AgPro

导航

背包问题--贪心

#include <iostream>
using namespace std;


int main()
{
	int n = 3;
	int c = 8;
	int w[3] = {4,3,2}; 
	int v[3] = {5,2,1};	
	float x[3];
	int i;

	//1.Kanpsack
	//sort(w,v)
	for ( i=0; i<n; i++ )
		x[i] = 0;
	float cap = (float)c;
	for ( i=0; i<n; i++ )
	{
		if (w[i]>cap)
			break;
		x[i] = 1;
		cap -= w[i];
	}
	if ( i<n )
		x[i] = cap/w[i];

	//2.MaxValue
	float total = 0;
	for ( i=0; i<n; i++ )
		total += x[i]*v[i];
	cout << "TotolValue: ";  
	cout << total << endl;   

	cout << "Knapsack Array: ";
	for ( i=0; i<n; i++ )
		cout << x[i] << " ";
	cout << endl;

	return 0; 
}

posted on 2010-06-13 15:09  AgPro  阅读(205)  评论(0编辑  收藏  举报