2214 knapsack problemAccept:6 Submit:9
Time limit:3000 mSec Memory limit:32768 KB problem Description
Given a set of n items, each with a weight w[i] and a value v[i], determine a-to-choose the items into a knapsack so T Hat The total weight are less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can is only chosen once).
Input
The first line contains the integer T indicating to the number of test cases.
For each test case, the first line contains the integers n and B.
Following n lines provide the information of each item.
The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively.
1 <= Number of test cases <= 100
1 <= N <= 500
1 <= B, W[i] <= 1000000000
1 <= v[1]+v[2]+...+v[n] <= 5000
All the inputs is integers.
Output
For each test case, output the maximum value.
Sample INPUT15 1512 101 2 sample Output15 source sixth Fujian College student Program Design contest-Replay (thanks to the organizer of Huaqiao University) topic: give you T Group of data, each group has n items, a backpack capacity B, each has a volume and value. Ask you what the maximum value of the item in this backpack is. Each item can only be put in one backpack. How to solve the problem: first of all, this is clearly seen as a 01 backpack. But the backpack is very large, and the volume of the goods is very large, but the total value is very small. Dp[i] Indicates the maximum value of a backpack capacity of I,so let's change the meaning of this dp[] array, Dp[i] represents the minimum capacity required to load value I.
#include <stdio.h> #include <algorithm> #include <string.h>using namespace std;const int maxn = 550; const int INF = 0x3f3f3f3f;int W[MAXN], v[maxn];int dp[5500];int main () { int T, n, B; scanf ("%d", &t); while (t--) { scanf ("%d%d", &n,&b); int V = 0; for (int i = 1; I <= n; i++) { scanf ("%d%d", &w[i],&v[i]); V + = V[i]; } Memset (Dp,inf,sizeof (DP)); Dp[0] = 0; for (int i = 1, i <= N; i++) {for (int j = V; J >= V[i]; j--) { Dp[j] = min (dp[j],dp[j-v[i]]+w[i]); printf ("%d", dp[j]); } } int ans = 0; for (int i = V; I >= 0, i--) { if (Dp[i] <= B) { ans = i; break; } } printf ("%d\n", ans); } return 0;}
Fzu 2214--knapsack problem —————— "oversized backpack with 01 backpacks"