背包问题-最小值-空间恰好是j
背包问题-最小价值-空间恰好\(j\)
一、\(01\)背包
求价值最小值:初始化\(f[0][0] = 0\), 其余是\(INF\)
例子:给你一堆物品,每个物品有一定的体积和对应的价值,每个物品只能选一个,求 总体积恰好是\(m\)的 最小价值
输入
4 5
1 2
2 4
3 4
4 5
输出
7
1、二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
int n, m;
int f[N][N];
int main() {
//文件输入
freopen("QiaHao_01_Min.in", "r", stdin);
scanf("%d %d", &n, &m);
memset(f, 0x3f, sizeof f); //预求最小,先设最大
f[0][0] = 0; //前0个物品中选择,装满0个空间,获得的最小值为0
for (int i = 1; i <= n; i++) {
int v, w;
scanf("%d %d", &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);
}
}
printf("%d\n", f[n][m]);
return 0;
}
2、一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
int n, m;
int f[N];
int main() {
//文件输入
freopen("QiaHao_01_Min.in", "r", stdin);
scanf("%d %d", &n, &m);
memset(f, 0x3f, sizeof f);
f[0] = 0;
for (int i = 1; i <= n; i++) {
int v, w;
scanf("%d %d", &v, &w);
for (int j = m; j >= v; j--)
f[j] = min(f[j], f[j - v] + w);
}
printf("%d\n", f[m]);
return 0;
}
二、完全背包
求价值最小值:初始化\(f[0][0] = 0\), 其余是\(INF\)
例子:给你一堆物品,每个物品有一定的体积和对应的价值,每个物品可以选无数多个,求 总体积恰好是\(m\)的 最小价值
输入
4 5
1 2
2 4
3 4
4 5
输出
7
1、二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
int n, m;
int f[N][N];
int main() {
scanf("%d %d", &n, &m);
memset(f, 0x3f, sizeof f);
f[0][0] = 0;
for (int i = 1; i <= n; i++) {
int v, w;
scanf("%d %d", &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][j - v] + w);
}
}
printf("%d\n", f[n][m]);
return 0;
}
2、一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110, INF = 0x3f3f3f3f;
int n, m;
int f[N];
int main() {
//文件输入
freopen("QiaHao_WQ_Min.in", "r", stdin);
scanf("%d %d", &n, &m);
memset(f, 0x3f, sizeof f);
f[0] = 0;
for (int i = 1; i <= n; i++) {
int v, w;
scanf("%d %d", &v, &w);
for (int j = v; j <= m; j++)
f[j] = min(f[j], f[j - v] + w);
}
printf("%d\n", f[m]);
return 0;
}