状态转移方程
初始的状态转移方程
for(int i = 0; i <= n; i++){for(int v = w[i]; v <= V; v++){dp[i][v] = max(dp[i - 1][v], dp[i - 1][v - w[i]] + c[i]);}}
利用滚动数组压缩空间(必须要逆序)
for(int i = 0; i <= n; i++){for(int v = V; v >= w[i]; v--){dp[v] = max(dp[v], dp[v - w[i]] + c[i]);}}
输出过程代码
输入
5 8
3 5 1 2 2
4 5 2 1 3
输出:dp[8] ~ dp[1]
i = 1,4 4 4 4 4 4 0 0
i = 2, 9 5 5 5 4 4 0 0
i = 3, 9 7 7 6 6 4 2 2
i = 4, 9 7 7 6 6 4 2 2
i = 5, 10 9 9 7 6 5 3 2
#include<cstdio>#include<algorithm>using namespace std;const int maxn = 100;const int maxv = 1000;int w[maxn], c[maxn], dp[maxv];//w重量、c价值int main(){int n, V;//V是容量,n是物品数量scanf("%d%d", &n, &V);for(int i = 1; i <= n; i++) scanf("%d", &w[i]);for(int i = 1; i <= n; i++) scanf("%d", &c[i]);for(int v = 0; v <= V; v++) dp[v] = 0;for(int i = 1; i <= n; i++){for(int v = V; v >= w[i]; v--){dp[v] = max(dp[v], dp[v - w[i]] + c[i]);printf("v = %d, dp[%d] = %d ", v, v, dp[v]);}printf("\n");for(int i = V; i >= 1; i--) printf("%d ",dp[i]);printf("\n");}}
题解代码
#include<cstdio>#include<algorithm>using namespace std;const int maxn = 100;const int maxv = 1000;int w[maxn], c[maxn], dp[maxv];//w重量、c价值int main(){int n, V, ans = 0;//V是容量,n是物品数量scanf("%d%d", &n, &V);for(int i = 1; i <= n; i++) scanf("%d", &w[i]);for(int i = 1; i <= n; i++) scanf("%d", &c[i]);for(int v = 0; v <= V; v++) dp[v] = 0;for(int i = 1; i <= n; i++){for(int v = V; v >= w[i]; v--){dp[v] = max(dp[v], dp[v - w[i]] + c[i]);ans = max(ans, dp[v]);}}printf("%d", ans);}
