Bone Collector HDU - 2602(揹包入門題)

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 92595
Accepted Submission(s): 37866

Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output
One integer per line representing the maximum of the total value (this number will be less than 231).

Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output
14

問題鏈接
HDU - 2602

問題簡述
骨頭收集者喜歡收集骨頭,現在有n種骨頭,每種骨頭的價值和體積不同,而骨頭收集者的揹包容量有限,請你幫他找出價值最大的裝入法。

問題分析
揹包入門題,依次篩查比較出價值最大者。
在同樣的揹包容量下,如果前面的骨頭體積小於等於揹包容積,則考慮放或者不放,放的話:將當前的揹包體積減去骨頭體積再加上骨頭價值——此爲放的價值,不放的話:揹包內裝的骨頭情況依舊。

二維數組揹包:(列表法)

#include <cstring>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define maxn 1005
int n,bag,v[maxn],w[maxn],dp[maxn][maxn];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(v,0,sizeof(v));
		memset(w,0,sizeof(w));
		memset(dp,0,sizeof(dp));
		scanf("%d%d",&n,&bag);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&v[i]);
		}
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&w[i]);
		}
		for(int i=1;i<=n;i++)//列表法,列出每種情況;i爲只考慮前i種物品時 
		for(int j=0;j<=bag;j++)//j代表揹包容量 
		{
			if(j>=w[i])
			{
				dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);
			}
			else
				dp[i][j]=dp[i-1][j];
		}
		printf("%d\n",dp[n][bag]);
	}
}

一維數組揹包:(滾動法)

#include <cstring>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define maxn 1005
int n,bag,v[maxn],w[maxn],dp[maxn];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(v,0,sizeof(v));
		memset(w,0,sizeof(w));
		memset(dp,0,sizeof(dp));
		scanf("%d%d",&n,&bag);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&v[i]);
		}
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&w[i]);
		}
		for(int i=1;i<=n;i++)//滾動法,只考慮當前情況 
		for(int j=bag;j>=w[i];j--)//考慮到正序時i=i-1時dp[j]的值會被覆蓋導致錯誤,故而使用逆序  
		{
				dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
		}
		printf("%d\n",dp[bag]);//最後注意換行 
	}
}

一維數組相較於二維數組更加節省空間,然而若是要打印每種情況的話,由於一維數組進行了覆蓋操作,導致無法打印。

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