Skip to content

Instantly share code, notes, and snippets.

@time-river
Created July 31, 2018 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save time-river/887bd913fc4b0680fd059705fae3f78b to your computer and use it in GitHub Desktop.
Save time-river/887bd913fc4b0680fd059705fae3f78b to your computer and use it in GitHub Desktop.
背包九讲之完全背包,恰好装满,一维(滚动)数组
/*
* 背包九讲之完全背包 恰好装满 滚动数组
* from: http://acm.hdu.edu.cn/showproblem.php?pid=1114
* reference: https://blog.csdn.net/liujc_/article/details/44003167
*/
#include <bits/stdc++.h>
#define PMAX 1000000001
using namespace std;
/*
* d[i] = min{ d[i], d[i-V[j]] + W[j] }
*/
int piggy_bank(int P[], int W[], int n, int V) {
int *d = new int[V+1];
int w;
for (int i = 0; i <= V; i++) {
if (i == 0)
d[i] = 0;
else
d[i] = PMAX;
}
for (int i = 0; i < n; i++) {
for (int j = 1; j <= V; j++) {
if (j >= W[i]) {
w = d[j-W[i]] + P[i];
d[j] = d[j] < w ? d[j] : w;
} else {
d[j] = d[j];
}
}
}
w = d[V];
delete d;
return w;
}
int main() {
int T;
cin >> T;
while (T--) {
int E, F, N, d;
int *P, *W;
cin >> E >> F;
cin >> N;
P = new int[N];
W = new int[N];
for (int i = 0; i < N; i++)
cin >> P[i] >> W[i];
d = piggy_bank(P, W, N, F-E);
if (d != PMAX)
cout << "The minimum amount of money in the piggy-bank is " << d << "." << endl;
else
cout << "This is impossible." << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment