1. 程式人生 > >動態規劃: 揹包問題(施工中)

動態規劃: 揹包問題(施工中)

參考自如下兩篇部落格:

http://www.cnblogs.com/tanky_woo/archive/2010/07/31/1789621.html
http://blog.csdn.net/insistgogo/article/details/11081025

一、0-1揹包問題

#include <iostream>
#include <algorithm>
using namespace std;
int vol, n, f[11];
int ZeroOnePack(int cost[4], int value[4]){
	for (int i = 1; i <= n; i++)
		for (int v = vol; v >= cost[i]; v--)
			f[v] = max(f[v], f[v - cost[i]] + value[i]);
	return f[vol];
}
int main(){
	int cost[4];
	int value[4];
	while (cin >> vol >> n){
		memset(f, 0, sizeof(f));	//初始化:無需裝滿揹包	
		//		memset(f, -100, sizeof(f));	//初始化:恰好裝滿揹包
		f[0] = 0;
		for (int i = 1; i <= n; i++)
			cin >> cost[i] >> value[i];
		cout << ZeroOnePack(cost, value) << endl;
	}
	return 0;
}


二、完全揹包問題

#include <iostream>
#include <algorithm>
using namespace std;
int vol, n, f[11];
int CompletePack(int cost[4], int value[4]){
	for (int i = 1; i <= n; i++)
		for (int v = cost[i]; v <= vol; v++)
			f[v] = max(f[v], f[v - cost[i]] + value[i]);
	return f[vol];
}
int main(){
	int cost[4];
	int value[4];
	while (cin >> vol >> n){
		memset(f, 0, sizeof(f));	//初始化:無需裝滿揹包		
//		memset(f, -100, sizeof(f));	//初始化:恰好裝滿揹包
		f[0] = 0;
		for (int i = 1; i <= n; i++)
			cin >> cost[i] >> value[i];
		cout << CompletePack(cost, value) << endl;
	}
	return 0;
}


三、分組揹包問題

#include <iostream>
#include <algorithm>
using namespace std;
int vol, N, K;
int f[11];
int GroupPack(int cost[10][10], int value[10][10], int cnt[10]){
	for (int k = 1; k <= K; k++)
		for (int v = vol; v >= 0; v--)
			for (int i = 1; i <= cnt[k]; i++)
				if (v >= cost[k][i])
					f[v] = max(f[v], f[v - cost[k][i]] + value[k][i]);
	return f[vol];
}
int main(){
	int cost[10][10], value[10][10], cnt[10];
	while (cin >> vol >> N >> K){
		for (int i = 1; i <= K; i++){
			cin >> cnt[i];
			for (int j = 1; j <= cnt[i]; j++)
				cin >> cost[i][j] >> value[i][j];
		}
		memset(f, 0, sizeof(f));	//初始化:無需裝滿揹包		
		//			memset(f, -100, sizeof(f));	//初始化:恰好裝滿揹包
		f[0] = 0;
		cout << GroupPack(cost, value, cnt) << endl;
	}
	return 0;
}


f[0] f[1] f[2] f[3] f[4] f[5] f[6] f[7] f[8] f[9] f[10]