Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
背包九讲之完全背包,恰好装满,一维(滚动)数组
/*
* 背包九讲之完全背包 恰好装满 滚动数组
* 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
You can’t perform that action at this time.