背包问题的记忆化搜索写法
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 1010; int n, m; int v[N], w[N]; int f[1010][1010]; int dfs(int curu, int curv) { if(f[curu][curv] > 0) return f[curu][curv]; if(curu == n) return 0; int res = 0; if(curv - v[curu] < 0) res = dfs(curu + 1, curv); else { res = max(dfs(curu + 1, curv), dfs(curu + 1, curv - v[curu]) + w[curu]); } return f[curu][curv] = res; } int main() { cin >> n >> m; for(int i = 0; i < n; i ++ ) cin >> v[i] >> w[i]; cout << dfs(0, m) << endl; return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 1010; int n, m; int w[N], v[N]; int f[N]; int dfs(int curv) { if(f[curv]) return f[curv]; for(int i = 0; i < n; i ++ ) { if(curv >= v[i]) { f[curv] = max(f[curv], dfs(curv - v[i]) + w[i]); } } return f[curv]; } int main() { cin >> n >> m; for(int i = 0; i < n; i ++ ) cin >> v[i] >> w[i]; cout << dfs(m) << endl; return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 101; int n, m; int f[N][N], s[N], w[N], v[N]; int dfs(int curu, int curv) { if(f[curu][curv]) return f[curu][curv]; if(curu == n) return 0; int res = 0; for(int i = 0; i * v[curu] <= curv && i <= s[curu]; i ++ ) { res = max(res, dfs(curu + 1, curv - i * v[curu]) + w[curu] * i); } return f[curu][curv] = res; } int main() { cin >> n >> m; for(int i = 0; i < n; i ++ ) cin >> v[i] >> w[i] >> s[i]; cout << dfs(0, m) << endl; return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 1010; int n, m; int f[N][N], s[N]; int w[N][N], v[N][N]; int dfs(int group, int curv) { if(f[group][curv]) return f[group][curv]; if(group > n) return 0; int res = dfs(group + 1, curv); for(int i = 0; i < s[group]; i ++ ) { if(curv < v[group][i]) continue; res = max(res, dfs(group + 1, curv - v[group][i]) + w[group][i]); } return f[group][curv] = res; } int main() { cin >> n >> m; for(int i = 0; i < n; i ++ ) { cin >> s[i]; for(int j = 0; j < s[i]; j ++ ) { cin >> v[i][j] >> w[i][j]; } } cout << dfs(0, m) << endl; return 0; }