完全背包变形,有min和max两个写法,体会两种写法的不同之处
题目链接
ACcode
//重量作为价值,背包容量开到很大,购买价格作为背包
#include<bits/stdc++.h>
using namespace std;
const int M = 1e5 + 9;
int dp[M], w[M], v[M];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, h;cin >> n >> h;
for (int i = 1;i <= n;i++)cin >> w[i] >> v[i];
for (int i = 1;i <= n;i++) {
for (int j = v[i];j <= 100000;j++) {//背包容量开到很大,为了让完全背包跑完
dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
}
}
for (int i = 1;i < M;i++) {
if (dp[i] >= h) {
cout << i;
return 0;
}
}
}
//花费作为价值,背包容量最大为h+5000,dp[j]存的是购买j磅干草花费的钱
#include<bits/stdc++.h>
using namespace std;
const int M = 1e5 + 8;
int dp[M], w[M], v[M];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, h;cin >> n >> h;
for (int i = 1;i <= 55000;i++)dp[i] = 1e9;
for (int i = 1;i <= n;i++)cin >> w[i] >> v[i];
for (int i = 1;i <= n;i++) {
for (int j = w[i];j <= h + 5000;j++) {
dp[j] = min(dp[j], dp[j - w[i]] + v[i]);
}
}
int ans = 1e9;
for (int i = h;i <= h + 5000;i++) {
ans = min(ans, dp[i]);
}
cout << ans;
return 0;
}