#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 = 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; }
标签:curv,背包,group,int,dfs,curu,搜索,include,写法 From: https://www.cnblogs.com/zk6696/p/17827786.html