hdu 2602 Bone Collector(01背包)
题意:给出包裹的大小v,然后给出n块骨头的价值value和体积volume,求出一路下来包裹可以携带骨头最大价值
思路:01背包
1.二维数组(不常用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<stdio.h> #include<math.h> using namespace std; int dp[1100][1100]; int main() { int i,j; int t,n,_v;//测试用例个数,物品种类,背包大小 int c[1100],v[1100];//花费,价值 scanf("%d",&t); while(t--) { scanf("%d%d",&n,&_v); for(j=0; j<=_v; ++j)dp[0][j]=0; for(i=1; i<=n; ++i)scanf("%d",&v[i]); for(i=1; i<=n; ++i)scanf("%d",&c[i]); for(i=1; i<=n; ++i) { for(j=0; j<c[i]; ++j)dp[i][j]=dp[i-1][j]; for(j=c[i]; j<=_v; ++j) { if(dp[i-1][j-c[i]]+v[i]>dp[i-1][j])dp[i][j]=dp[i-1][j-c[i]]+v[i]; else dp[i][j]=dp[i-1][j]; } } printf("%d\n",dp[n][_v]); } return 0; }
2.一维数组(之后 多重、完全背包 的解法 皆采用一维数组)
1...n
_v...0
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<stdio.h> using namespace std; int dp[1100]; int main() { int i,j; int t,n,_v;//测试用例个数,物品种类,背包大小 int c[1100],v[1100];//花费,价值 scanf("%d",&t); while(t--) { scanf("%d%d",&n,&_v); for(j=0; j<=_v; ++j)dp[j]=0; for(i=1; i<=n; ++i)scanf("%d",&v[i]); for(i=1; i<=n; ++i)scanf("%d",&c[i]); for(i=1; i<=n; ++i) for(j=_v; j>=c[i]; --j) if(dp[j-c[i]]+v[i]>dp[j])dp[j]=dp[j-c[i]]+v[i]; printf("%d\n",dp[_v]); } return 0; }
附一道01背包好题:http://acm.csu.edu.cn/OnlineJudge/problem.php?cid=2071&pid=0