FAQ | About Virtual Judge | Forum | Discuss | Open Source Projec
题意 : 01背包的典型例题,题意就不BB了,此题背包容量过大,内存会超~~
思路: 根据01背包的思想,满足在背包容量以内,用最小的容量,装价值最大的物品。但是此题 背包容量过大,而价值之和的最大值只有5000,我们可以转换思路,利用01背包的思想,用最大价值来求最小容量;即为,把价值之和看作是背包的容量,进行背包。
代码:
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<map>
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
typedef long long ll;
using namespace std;
#define N 5100
ll dp[N],w[N]; ///此时的dp[i]表示的是;价值为i时的最小容量为dp[i];
int v[N];
int main()
{
int T,i,n,sum;
ll V;
scanf("%d",&T);
while(T--)
{
scanf("%d%I64d",&n,&V);
sum=0;
for(i=1;i<=n;i++)
{
scanf("%I64d%d",&w[i],&v[i]);
sum=sum+v[i];
}
memset(dp,1000000010,sizeof(dp)); ///要求最小容量,初始化为最大值;
dp[0]=0;
for(i=1;i<=n;i++)
{
for(int j=sum;j>=v[i];j--)
dp[j]=min(dp[j],dp[j-v[i]]+w[i]);
}
for(i=sum;i>=0;i--)
{
if(dp[i]<=V)
{
printf("%d\n",i); ///此处输出i,即为满足条件的最大价值
break;
}
}
}
return 0;
}