Uva10130-SuperSale (01 backpack)
Question: uva10130-SuperSale (01 backpack)
Question: Supermarket sales. There are n items, each of which has the corresponding value and weight. One family wants to go to the supermarket to buy things. Each person can only buy one item for each type of sale. They can take many different items but can take them. Give everyone the maximum weight they can take, and ask such a family to obtain the maximum value they can get from purchasing.
Solution: 01 backpack. Dp [j] = Max (dp [j], dp [j-W] + P); W is the weight of the product, and P is the value of the product.
Code:
#include
#include
const int N = 10005;const int maxn = 35;int dp[maxn];int object[N][2];int Max (const int a, const int b) { return a > b ? a: b; }int main () {int t;int n, g;int w;int ans;scanf ("%d", &t);while (t--) {scanf ("%d", &n);for (int i = 0; i < n; i++)scanf ("%d%d", &object[i][0], &object[i][1]);scanf ("%d", &g);memset (dp, 0, sizeof (dp));for (int i = 0; i < n; i++) for (int j = maxn - 5; j >= object[i][1]; j--)dp[j] = Max(dp[j], dp[j - object[i][1]] + object[i][0]);ans = 0;for (int i = 0; i < g; i++) {scanf ("%d", &w);ans += dp[w];}printf ("%d\n", ans);}return 0;}