51Nod 1085 背包问题
2017-11-15 22:04
274 查看
题意:在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。
解题思路:dp经典背包问题.dp[i][j]表示从第i个物品开始挑选总重量小于j时,总价值的最大值。递推式:dp
[j]=0,j<w[i]时,dp[i][j]=dp[i+1][j];其余情况dp[i][j]=max(dp[i+1][j],dp[i+1][j-w[i]]+v[i]),也就是第i个物品选与不选的两种情况。要注意的是数组的范围,数组开小了居然是TLE。。。
代码:
解题思路:dp经典背包问题.dp[i][j]表示从第i个物品开始挑选总重量小于j时,总价值的最大值。递推式:dp
[j]=0,j<w[i]时,dp[i][j]=dp[i+1][j];其余情况dp[i][j]=max(dp[i+1][j],dp[i+1][j-w[i]]+v[i]),也就是第i个物品选与不选的两种情况。要注意的是数组的范围,数组开小了居然是TLE。。。
代码:
#include <iostream> #include <algorithm> #include <cstring> #include <string> #include <cstdio> #include <cmath> #include <vector> #include <set> #include <map> #include <queue> using namespace std; const int maxn=110; const int maxm=10010; int dp[maxn][maxm]; int w[maxn],v[maxn]; int n,m; void DP() { for(int i=n-1;i>=0;i--) { for(int j=1;j<=m;j++) { if(j<w[i])dp[i][j]=dp[i+1][j]; else dp[i][j]=max(dp[i+1][j],dp[i+1][j-w[i]]+v[i]); } } printf("%d\n",dp[0][m]); } int main() { while(scanf("%d%d",&n,&m)==2) { for(int i=0;i<n;i++) { scanf("%d%d",&w[i],&v[i]); } for(int j=0;j<=m;j++) { dp [j]=0; } DP(); } return 0; }
相关文章推荐
- 51nod 1085 背包问题【01背包】
- 51Nod 1085 背包问题
- 51nod 1085 背包问题
- 【51Nod】1085 - 背包问题(01背包)
- 51nod--1085--背包问题
- 51nod 1085 背包问题01
- 【51NOD-0】1085 背包问题
- 51Nod 1085 背包问题(01背包 )
- 51nod 1085 背包问题
- 【51Nod】1085 - 背包问题【01背包】
- 51nod 1085 背包问题【01背包】
- 51nod 1085 背包问题
- 51nod 1085 背包问题<水过>
- 51Nod-1085-背包问题
- 【51nod 1085】背包问题(0-1背包模板)
- 51Nod 1085背包问题(dp)
- 51Nod 1085 背包问题
- 51nod 1085 背包问题(01背包)
- 51nod 1085 背包问题
- 51Nod-1085 背包问题