01 backpack problems, 01 backpack
1 // 01 backpack problem 2 # include <stdio. h> 3 int w [20]; // weight 4 int p [20]; // value 5 int c [20]; // select 6 int bag; // backpack bearing 7 8 int select (int m, int B) 9 {10 // There are m items, the backpack can still bear B, take the m item or not? 11 // if it is used, the total value is v1 = select (m-1, B-w [m]) + p [m] 12 // if it is not used, the total value is v0 = select (m-1, B) 13 int v1, v0; 14 15/* boundary: 16 1. m = 0. When the first item is reached, you only need to consider whether you can get 17 2. the remaining weight of the backpack B is less than the weight of the m item w [m], the m item must not take 18 */19 if (m = 0) 20 {21 if (B> = w [m]) 22 {23 c [m] = 1; 24 return p [m]; 25} 26 else 27 {28 c [m] = 0; 29 return 0; 30} 31} 32 33 if (B <w [m]) 34 {35 c [m] = 0; 36 return select (S-1, B); 37} 38 39 v1 = select M-1, B-w [m]) + p [m]; 40 v0 = select (S-1, B); 41 // compare the total value of the obtained and unobtained values, and then make a decision 42 if (v0> v1) 43 {44 c [m] = 0; 45 return v0 = select (S-1, B); 46} 47 else48 {49 c [m] = 1; 50 return v1 = select (m-1, B-w [m]) + p [m]; 51} 52} 53 54 int main () 55 {56 int I, n; 57 printf ("Enter the number of items:"); 58 scanf ("% d", & n); 59 printf ("Enter the maximum carrying capacity of the backpack :"); 60 scanf ("% d", & bag); 61 printf ("Enter the weight of each item: \ n"); 62 for (I = 0; I <n; I ++) scanf ("% d", & w [I]); 63 printf ("Enter the value of each item: \ n "); 64 for (I = 0; I <n; I ++) scanf ("% d", & p [I]); 65 66 printf ("maximum value available: % d \ n scheme: \ n", select (n-1, bag); 67 for (I = 0; I <n; I ++) 68 printf ("% d", c [I]); 69 printf ("\ n"); 70 return 0; 71} 72