一、01背包
1、最小值
求价值最小值:初始化\(f[0][0] = 0\), 其余是\(INF\)
例子:给你一堆物品,每个物品有一定的体积和对应的价值,每个物品只能选一个,求总体积恰好是\(m\)的最小价值
输入
4 5
1 2
2 4
3 4
4 5
输出
7
二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
int n, m;
int f[N][N];
int main() {
cin >> n >> m;
memset(f, INF, sizeof f);
f[0][0] = 0;
for (int i = 1; i <= n; i++) {
int v, w;
cin >> v >> w;
for (int j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v) f[i][j] = min(f[i][j], f[i - 1][j - v] + w);
}
}
cout << f[n][m] << endl;
return 0;
}
一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
int n, m;
int f[N];
int main() {
cin >> n >> m;
memset(f, INF, sizeof f);
f[0] = 0;
for (int i = 1; i <= n; i++) {
int v, w;
cin >> v >> w;
for (int j = m; j >= v; j--)
f[j] = min(f[j], f[j - v] + w);
}
cout << f[m] << endl;
return 0;
}