01揹包問題實現源碼

經典問題,物品個數爲n,揹包重量爲v,則時間複雜度爲O(nv)。

空間複雜度爲O(v)。

不過如果要得到選擇的最終結果,則需要把中間結果都記錄下來,空間複雜度只能也用O(nv)。

#include <iostream>
using namespace std;

int max(int a,int b) {
	return a>=b ? a : b;
}

int bag_use_one_array (
		const int weight[], 
		const int value[], 
		const int item_size, 
		const int bag_weight) {

	int max_value[bag_weight+1];
	for (int i=0; i<=bag_weight; i++) {
		max_value[i] = 0;
	}

	for (int i=0; i<item_size; i++) {
		for (int w=bag_weight; w>=1; w--) {
			if (weight[i] <= w) {
				//max_value[w] = max(max_value[w], max_value[w-weight[i]]+value[i]);
				if ( max_value[w] >= max_value[w-weight[i]]+value[i]) {
				} else {
					max_value[w] = max_value[w-weight[i]]+value[i];
				}
				cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w] << endl;
			}
		}
		cout << endl;
	}

	cout << "max value is : " << max_value[bag_weight] << endl;
	cout << endl;

	return max_value[bag_weight];
}

int bag_get_best_choice (
		const int weight[], 
		const int value[], 
		const int item_size, 
		const int bag_weight) {

	int max_value[bag_weight+1][item_size+1];
	for (int i=0; i<=bag_weight; i++) {
		max_value[i][0] = 0;
	}

	for (int j=0; j<=item_size; j++) {
		max_value[0][j] = 0;
	}

	for (int i=1; i<=item_size; i++) {
		for (int w=bag_weight; w>=1; w--) {
			if (weight[i-1] <= w) {
				if ( max_value[w][i-1] >= max_value[w-weight[i-1]][i-1]+value[i-1]) {
					max_value[w][i] = max_value[w][i-1];
				} else {
					max_value[w][i] = max_value[w-weight[i-1]][i-1]+value[i-1];
				}
			} else {
			    max_value[w][i] = max_value[w][i-1];
			}
			cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w][i] << endl;
		}
		cout << endl;
	}

	cout << "max value is : " << max_value[bag_weight][item_size] << endl;
	cout << endl;

	int choice[item_size];
	int weight_choice = bag_weight;
	for (int i=item_size-1; i>=0; i--) {
		if (max_value[weight_choice][i+1] 
				> max_value[weight_choice][i]) {
		    choice[i]=1;
			weight_choice -= weight[i];
		} else {
		    choice[i]=0;
		}
	}

	for (int i=0; i<item_size; i++) {
		cout << choice[i] << " ";
	}
	cout << endl;

	return max_value[bag_weight][item_size];
}

int main() {
	const int item_size = 5;
	const int bag_weight = 15;

        int weight[item_size] = {12,1,4,1,2};
	int value[item_size] = {4,2,10,1,2};

	//bag_use_one_array(weight, value, item_size, bag_weight);
	bag_get_best_choice(weight, value, item_size, bag_weight);

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章