经典的01背包问题模板
这里提供两种做法:
#include #include using namespace std;//Mystery_Sky//二维01背包模板 #define M 1000int f[M][M], ans;int v, m, c[M], w[M];int main() { scanf("%d%d", &v, &m); for(int i = 1; i <= m; i++) scanf("%d%d", &c[i], &w[i]); for(int i = 1; i <= m; i++) for(int j = 0; j <= v; j++) { if(j >= c[i]) f[i][j] = max(f[i-1][j], f[i-1][j-c[i]]+w[i]); else f[i][j] = f[i-1][j]; } printf("%d\n", f[m][v]); return 0;}
#include #include using namespace std;//Mystery_Sky//一维01背包模板 #define M 1000int f[M], c[M], w[M];int ans, v, m;int main() { scanf("%d%d", &v, &m); for(int i = 1; i <= m; i++) scanf("%d%d", &c[i], &w[i]); for(int i = 1; i <= m; i++) for(int j = v; j >= c[i]; j--) { f[j] = max(f[j], f[j-c[i]]+w[i]); } printf("%d\n", f[v]); return 0;}