Problem Description
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
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
Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1
Sample Output
14
01背包的入门题 一般0-1背包的问题会是,总容积或总承重为c,
有n个物品,体积或质量为wi,价值为pi.计算放哪几个物品可以使价值最高
我们将在总重量不超过Y的前提下,前i种物品的总价格所能达到的最高值定义为A(i,Y)。
A(i,Y)的递推关系为:
A(0,Y) = 0
A(i,0) = 0
如果wi> Y, A(i, Y) = A(i - 1, Y)
如果wi≤ Y, A(i, Y) = max { A(i - 1, Y), pi + A(i - 1, Y - wi) }
最终得到的A(n,c)则是最终答案即最高价值.
我们先放第一个物品,因为第一个物品质量为1,所以当盒子的承重Y大于1的时候才可以放,也就是根据前面的式子
如果wi> Y, A(i, Y) = A(i - 1, Y)
如果wi≤ Y, A(i, Y) = max { A(i - 1, Y), pi + A(i - 1, Y - wi) }
以此类推。
当然这个Y并不是指盒子最大承重,而是动态规划的递推。
for(i=1;i<=n; i++) //动态规划实现0-1背包
{
for(j=0; j<=c; j++)//c为总承重量,j为上面描述的Y
{
if(j>=w[i])f[i][j]=max(f[i-1][j],f[i-1][j-w[i]]+v[i]);
else f[i][j]=f[i-1][j];
}
}
for (i = 1; i <= N; i++)
{
for (j = V; j >= volume[i]; j--)
{
d[j] = max(d[j], d[j - volume[i]]+ value[i]);
}
}
二维:
<strong>#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int s[1010];
int a[1010];
int dp[1010][1010];
int max(int x,int y)
{
return x>y?x:y;
}
int main()
{
int n,m,i,j,sum,bbs;
cin>>bbs;
while(bbs--)
{
cin>>n>>m;
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
cin>>s[i];//价值
}
for(i=1;i<=n;i++)
{
cin>>a[i]; //体积
<span style="white-space:pre"> </span>for(i=1;i<=n;i++)
{
for(j=0;j<=m;j++)//看0到v的体积空间从小到大能存多少的东西
{
if(j>=a[i])// //在j的背包下能放a【i】体积 的东西
{
dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+s[i]);
}
else dp[i][j]=dp[i-1][j];
}
}
cout<<dp[n][m]<<endl;
}
return 0;
}
</strong>
一维:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int s[1010];
int a[1010];
int dp[1010];
int main()
{
int n,m,i,j,sum,bbs;
cin>>bbs;
while(bbs--)
{
cin>>n>>m;
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
cin>>s[i];
}
for(i=1;i<=n;i++)
{
cin>>a[i];
}
for(i=1;i<=n;i++)
{
for(j=m;j>=a[i];j--)
{
dp[j]=max(dp[j],dp[j-a[i]]+s[i]);
}
}
cout<<dp[m]<<endl;
}
return 0;
}