Knapsack problem of algorithm analysis

The meaning of problems

Given a backpack deadweight of M, considering the n items, wherein the weight wi of the i-th item, the value of vi (1≤i≤n), filled article requires the knapsack, and so that the maximum value of the contents of the backpack.
There are two types knapsack problem (depending on whether the items can be separated), if the item can not be split, called the 0-1 knapsack problem (dynamic programming); If the item can be split, it is called knapsack problem (a greedy algorithm).

Code

#include <the iostream> 
the using namespace STD; 

#define NUM 50 

// assumed here w [], v [] have been sorted according to claim 
void Knapsack (int n, float M , float v [], float w [], float X []) 
{ 
    int I; 
     for (I =. 1; I <= n-; I ++) X [I] = 0; // initialize the array 
     a float C = M; 
     for (I =. 1; I <= n-; I ++) // hold all the items, and the X [I]. 1 = 
     { 
         IF (W [I]> C) BREAK; 
         X [I] =. 1; 
         C - = W [I]; 
     } 

     IF (I <= n) x [i] = c / w [i]; // to hold a portion of the article i 
 } 

 int main () 
 { 
     a float M = 50; // the weight of the backpack can fit 
     float w [] = {0, 10,20,30}; // here given the value of the items sorted in descending order 
     float v [] = {0,60,100,120} ;
       float x [NUM]; // ratio of each item stored into the backpack 

     int n-= (the sizeof (W) / the sizeof (W [0])) -. 1; 

     Knapsack (n-, M, V, W, X); 

     for (int I =. 1; I <= n-; I ++) 
         "loaded ratio:" cout << "Item" << << << I X [I] << endl; 
     return 0; 
 }

 

Guess you like

Origin www.cnblogs.com/khnl/p/11740323.html