经典的01背包问题模板
这里提供两种做法:
#include <iostream>
#include <cstdio>
using namespace std;
//Mystery_Sky
//二维01背包模板
#define M 1000
int 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
", f[m][v]);
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
//Mystery_Sky
//一维01背包模板
#define M 1000
int 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
", f[v]);
return 0;
}