解题思路:
注意事项:
数组大小要开足...
参考代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #define N 5000 using namespace std; int dp[N + 2], w[N + 2], c[N + 2]; int backPack01(int V, int n) { for (int i = 1; i <= n; i++) for (int j = V; j >= w[i]; j--) dp[j] = max(dp[j], dp[j - w[i]] + c[i]); return dp[V]; } int main(int argc, char** argv) { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) cin >> w[i] >> c[i]; cout << backPack01(m, n) << endl; return 0; }
//JXU4QzI4JXU0RUU1JXU2QjY0JXU5ODk4JXU4OUUzJXU1MTQ4JXU3RUQ5JXU2MjExJXU2NzAwJXU0RUIyJXU3MjMxJXU3Njg0JXU0RUJB #include <iostream> #include <stdio.h> #include <algorithm> #define MAX_N 210 #define MAX_V 5010 using namespace std; int n, W; int w[MAX_N], v[MAX_N]; int dp[MAX_N][MAX_V]; int cache[MAX_N][MAX_V]; bool vis[MAX_N][MAX_V]; int solve_dfs_a(int i, int j) { int res; if (i == n) res = 0; else if (j < w[i]) res = solve_dfs_a(i + 1, j); else res = max(solve_dfs_a(i + 1, j), solve_dfs_a(i + 1, j - w[i]) + v[i]); return res; } int solve_dfs(int index, int res) { int ans = 0; if (index == n || res <= 0) return 0; else { if (res - w[index] >= 0) ans = max(solve_dfs(index + 1, res - w[index]) + v[index], solve_dfs(index + 1, res)); else ans = solve_dfs(index + 1, res); } return ans; } int solve_dfs_m(int i, int j) { if (vis[i][j]) return cache[i][j]; int res; if (i == n) res = 0; else if (j < w[i]) res = solve_dfs_m(i + 1, j); else res = max(solve_dfs_m(i + 1, j), solve_dfs_m(i + 1, j - w[i]) + v[i]); vis[i][j] = true; cache[i][j] = res; return res; } int solve_dp() { dp[0][w[0]] = v[0]; // Init for (int i = 1; i <= n - 1; i++) { for (int j = 1; j <= W; j++) { if (j - w[i] >= 0) dp[i][j] = max(dp[i - 1][j - w[i]] + v[i], dp[i - 1][j]); else dp[i][j] = dp[i - 1][j]; } } int ans = 0; for (int j = 0; j <= W; j++) if (ans < dp[n - 1][j]) ans = dp[n - 1][j]; return ans; } int main() { cin >> n >> W; for (int i = 0; i < n; i++) cin >> w[i] >> v[i]; cout << solve_dp() << endl; //cout << solve_dfs_m(0, W) << endl; //cout << solve_dfs_a(0, W) << endl; //cout << solve_dfs(0, W) << endl; return 0; }
0.0分
0 人评分
弟弟的作业 (C++代码)浏览:1342 |
printf基础练习2 (C语言代码)浏览:324 |
【矩阵】 (C++代码)浏览:1000 |
C语言训练-亲密数 (C语言代码)浏览:697 |
字符串输入输出函数 (C语言代码)浏览:2645 |
sizeof的大作用 (C语言代码)浏览:1139 |
单词个数统计 (C语言代码)浏览:1046 |
数组输出 (C语言代码)浏览:749 |
C语言程序设计教程(第三版)课后习题6.10 (C语言代码)浏览:536 |
1052题解(链表操作)浏览:782 |