Given a set of n items, each with a weight w[i] and a value v[i], determine a way to choose the items into a knapsack so that the total weight is less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can be only chosen once).
The first line contains the integer T indicating to the number of test cases.
For each test case, the first line contains the integers n and B.
Following n lines provide the information of each item.
The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively.
1 <= number of test cases <= 100
1 <= n <= 500
1 <= B, w[i] <= 1000000000
1 <= v[1]+v[2]+...+v[n] <= 5000
All the inputs are integers.
For each test case, output the maximum value.
1 5 15 12 4 2 2 1 1 4 10 1 2Sample Output
15
思路:因为容量太大,所以不能按0-1背包问题去求解。注意到物品个数较小,而且价值和只有5000,所以可以逆向思维,求得对应价值下最小的重量,即dp[i]表示总价值为i是的最小重量是多少,则dp[j] = min(dp[j] , dp[j-val[i]]+vol[i]);最后从v(物品总价值开始判断)开始,找到第一个小于等于w(容量)的v即可。。。。
(我还不太懂,借用一下别人的。。。。)
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int dp[5005];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
while(n--)
{
int v[505],w[505];
memset(dp,0x3f3f3f3f,sizeof(dp));
int a,b;
scanf("%d%d",&a,&b);
int sum=0;
for(int i=1;i<=a;i++)
{
scanf("%d%d",&w[i],&v[i]);
sum+=v[i];
}
dp[0]=0;
for(int i=1;i<=a;i++)
{
for(int j=sum;j>=v[i];j--)
{
dp[j]=min(dp[j-v[i]]+w[i],dp[j]);
}
}
for(int i=sum;i>=0;i--)
{
if(dp[i]<=b)
{
printf("%d\n",i);
break;
}
}
}
}
return 0;
}