Backpack problems, 0-1 backpack Problems
-
Greedy
-
Description
-
Now there are a lot of items (they can be separated), and we know the value v and weight w of each item (1 <= v, w <= 10 ); if you have a backpack that can hold the weight of m (10 <= m <= 20), all you need to do is to pack the item into the backpack, this maximizes the total value of items in a backpack.
-
Input
-
Enter a positive integer n (1 <=n <= 5) In the first line, indicating that n groups of test data exist;
Then there is n test data. The first row of each group of test data has two positive integers s, m (1 <= s <= 10), and s indicates that there are s items. Each row in the next s line has two positive integers v, w.
-
Output
-
Outputs the value and value of the items in the backpack in each group of test data. Each output occupies one row.
-
Sample Input
-
13 155 102 83 9
-
Sample output
-
65
1 # include <stdio. h> 2 typedef struct value 3 {4 int v;/* value */5 int w;/* weight */6} thing; 7 int main () 8 {9 int n; 10 scanf ("% d", & n); 11 while (n --) 12 {13 int s, m, j, I = 0, sumv = 0, sumw = 0; 14 scanf ("% d", & s, & m); 15 thing a [s], t; 16 while (I! = S) 17 {18 scanf ("% d", & a [I]. v, & a [I]. w); 19 I ++; 20} 21 for (I = 0; I <s-1; I ++) 22 for (j = I; j <s; j ++) 23 {24 if (a [I]. v <a [j]. v) 25 {26 t = a [I]; 27 a [I] = a [j]; 28 a [j] = t; 29} 30} 31 int ww = 0, vv = 0; 32 I = 0; 33 while (sumw <m) 34 {35 ww = sumw; 36 vv = sumv; 37 sumw = sumw + a [I]. w; 38 sumv = sumv + a [I]. w * a [I]. v; 39 I ++; 40 while (I = s) 41 break; 42} 43 if (sumv> m) 44 sumv = vv + (m-ww) * a [I-1]. v; 45 printf ("% d \ n", sumv); 46} 47}