if(j>=w[i])
dp[i][j] = max(dp[i-1][j-w[i]]+v[i], dp[i-1][j]);
i代表前i件物品,j代表背包容量;
else
dp[i][j]=dp[i-1][j];
i
|
1
|
2
|
3
|
4
|
5
|
w
|
1
|
2
|
3 |
4
|
5
|
v
|
5
|
4
|
3
|
2
|
1
|
idpj
|
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8 | 9 |
10
|
0
|
0 | 0 | 0 | 0 |
0
|
0
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
5 | 5 | 5 |
5
|
5
|
5
|
5
|
5
|
5
|
5
|
2
|
0
|
5
|
5
|
9
|
9
|
9
|
9
|
9
|
9
|
9
|
9
|
3 |
0
|
5
|
5
|
9
|
9
|
9
|
12
|
12
|
12
|
12
|
12
|
4
|
0
|
5
|
5
|
9
|
9
|
9
|
12
|
12
|
12
|
12
|
14
|
5
|
0
|
5
|
5
|
9 |
9
|
9
|
12
|
12
|
12
|
12
|
14
|
/*
1 0
2 0
*/
动态规划求dp【5】【10】;
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #define N 1010 using namespace std; int w[N],v[N],dp[N][N]; int main() { int i,j,T,WW,VV; cin>>T; while(T--) { memset(dp,0,sizeof(dp)); cin>>WW>>VV; for(i=1;i<=WW;i++) cin>>v[i]; for(i=1;i<=WW;i++) cin>>w[i]; for(i=1;i<=WW;i++) { for(j=0;j<=VV;j++)//j=0//当当背包的承受量和商品的重量都为0时,价值都应加上;如果j=1时;不能加上价值;
{ if(j>=w[i]) dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]); else dp[i][j]=dp[i-1][j]; } } printf("%d ",dp[WW][VV]); } return 0; }