HDU 2602 Bone Collector 0/1背包,hdu2602
題目連結:HDU 2602 Bone Collector
Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 28903 Accepted Submission(s): 11789
Problem DescriptionMany 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 ?
InputThe 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.
OutputOne integer per line representing the maximum of the total value (this number will be less than 231).
Sample Input
15 101 2 3 4 55 4 3 2 1
Sample Output
14
AuthorTeddy
SourceHDU 1st “Vegetable-Birds Cup” Programming Open Contest
Recommendlcy | We have carefully selected several similar problems for you: 1203 2159 2955 2844 1087
經典0/1背包問題。
有N件物品和一個容量為V的背包,第i件物品的體積為v[i],價值為w[i],求解將哪些物品裝入背包才能使總價值最大。
這是最基礎的背包問題,每種物品只有一件,且只有兩種狀態:放與不放。
用子問題定義狀態:dp[i][v]表示前i件物品恰好放入一個容量為m的包中可獲得的最大價值。
狀態轉移方程:dp[i][m] = max(dp[i-1][m], dp[i-1][m-v[i]]+w[i]);
可轉化為一維情況:dp[m] = max(dp[m], dp[m-v[i]]+w[i]);
代碼:
#include <iostream>#include <cstdio>#include <cstring>using namespace std;int n, v, dp[1010], value[1010], volume[1010];int main(){ int t; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &v); for(int i = 1; i <= n; i++) scanf("%d", &value[i]); for(int i = 1; i <= n; i++) scanf("%d", &volume[i]); memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++) for(int j = v; j >= volume[i]; j--) dp[j] = max(dp[j], dp[j-volume[i]]+value[i]); printf("%d\n", dp[v]); } return 0;}
杭電2602 Bone Collector 01背包問題為何一直wrong?
有以下錯誤:
1.開闢數組單元的下標不能是變數,所以語句
const int maxn=1005;
應改為:
#define maxn 1005
2.不知開發環境是什麼樣的,如果是16位下的,
那麼
dp[1005][1005]
因數值太大需要改變編譯模式,否則就會出錯。
hdu 2602為何WA?
我把我ac的代碼發給你做參考吧,好好對比看一下,加油
#include <stdio.h>
#include<string.h>
int p[1001];
struct pp
{
int n;
int v;
}a[1001];
int MAX(int m,int n)
{
return m>n?m:n;
}
int main()
{
int t,m,v,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&v);
for(i=1;i<=m;i++)
{
scanf("%d",&a[i].n);
}
for(i=1;i<=m;i++)
{
scanf("%d",&a[i].v);
}
memset(p,0,sizeof(p));
for(i=1;i<=m;i++)
{
for(j=v;j>=0;j--)
if(j>=a[i].v)
p[j]=MAX(p[j],p[j-a[i].v]+a[i].n);
}
printf("%d\n",p[v]);
}
return 0;