背包
1.0/1背包
#include <bits/stdc++.h> using namespace std; #define ll long long #define INF 0x3f3f3f3f #define MAXN 300010 #define MAXM 3010 inline int read() { int x = 0,ff = 1;char ch = getchar(); while(!isdigit(ch)) { if(ch == '-') ff = -1; ch = getchar(); } while(isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * ff; } int V,n,ans,weigh[MAXN],value[MAXN],f[MAXN]; int main() { V = read(); n = read(); for(int i = 1; i <= n; ++i) { weigh[i] = read(); value[i] = read(); } for(int i = 1; i <= n; ++i) { for(int j = V; j >= weigh[i]; --j) { f[j] = max(f[j],f[j - weigh[i]] + value[i]); } } for(int i = 1; i <= V; ++i) ans = max(ans,f[i]); printf("%d\n",ans); }
2.完全背包
#include <bits/stdc++.h> using namespace std; #define ll long long #define INF 0x3f3f3f3f #define MAXN 300010 #define MAXM 3010 inline int read() { int x = 0,ff = 1;char ch = getchar(); while(!isdigit(ch)) { if(ch == '-') ff = -1; ch = getchar(); } while(isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * ff; } int V,n,ans,f[MAXN],v[MAXN],w[MAXN]; int main() { V = read(); n = read(); for(int i = 1; i <= n; ++i) { w[i] = read(); v[i] = read(); } for(int i = 1; i <= n; ++i) { for(int j = w[i]; j <= V; ++j) { f[j] = max(f[j],f[j - w[i]] + v[i]); } } for(int i = 1; i <= V; ++i) ans = max(ans,f[i]); printf("%d\n",ans); }
3.多重背包
#include <bits/stdc++.h> using namespace std; #define ll long long #define INF 0x3f3f3f3f #define MAXN 300010 #define MAXM 3010 inline int read() { int x = 0,ff = 1;char ch = getchar(); while(!isdigit(ch)) { if(ch == '-') ff = -1; ch = getchar(); } while(isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * ff; } int N,V,ans,w[MAXN],v[MAXN],n[MAXN],f[MAXM][MAXM]; int main() { N = read(); V = read(); for(int i = 1; i <= N; ++i) { n[i] = read(); w[i] = read(); v[i] = read(); } for(int i = 1; i <= N; ++i) { for(int k = 0; k <= n[i]; ++k){ for(int j = k * w[i]; j <= V; ++j) { f[i][j] = max(f[i][j],f[i - 1][j - k * w[i]] + k * v[i]); } } } for(int i = 1; i <= V; ++i) ans = max(ans,f[N][i]); printf("%d\n",ans); return 0; }
二进制优化:
#include <bits/stdc++.h> using namespace std; #define ll long long #define INF 0x3f3f3f3f #define MAXN 300010 #define MAXM 3010 template <typename T> inline void read(T &x) { x = 0; T ff = 1;char ch = getchar(); while(!isdigit(ch)) { if(ch == '-') ff = -1; ch = getchar(); } while(isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } x *= ff; } int N,V,size; ll w[MAXN],v[MAXN],n[MAXN],f[MAXN],ans; int main() { read(N); read(V); for(int i = 1; i <= N; ++i) { int x,y,z,t = 1; // n,w,v; read(x); read(y); read(z); while(t <= x) { w[++size] = y * t; v[size] = z * t; x -= t; t <<= 1; } if(x > 0) { w[++size] = y * x; v[size] = z * x; } } for(int i = 1; i <= size; ++i) { for(int j = V; j >= w[i]; --j) { f[j] = max(f[j],f[j - w[i]] + v[i]); } } for(int i = 1; i <= V; ++i) ans = max(ans,f[i]); printf("%lld\n",ans); return 0; }