Programming Algorithm-complete knapsack problem code (C)

Source: Internet
Author: User

Programming Algorithm-complete knapsack problem code (C)
Complete backpack problem code (C)

 

 

Question: There are n items whose weight and value are respectively w and v. From these items, select the items whose total weight does not exceed W and find the maximum value of the total value in all the selection schemes.

* You can select any number of items for each item.

 

Dynamic Planning: Add the largest combination to the array,First time complexity O (nW ^ 2),Second, time complexity O (nW).

Solution 1, max () indicates that either from the above or from the front.

 

Code:

 

/** Main. cpp ** Created on: 2014.7.17 * Author: spike * // * eclipse cdt, gcc 4.8.1 */# include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
# Include using namespace std; class Program {static const int MAX_N = 100; int n = 4, W = 5; int w [MAX_N] = }, v [MAX_N] = {3, 2, 4, 2}; int dp [MAX_N + 1] [MAX_N + 1]; public: void solve () {for (int I = 0; I
      
       Output:
       

 

 

result = 10


To save memory, you can useOne-dimensional arraySolve the problem.

 

Code:

 

/** Main. cpp ** Created on: 2014.7.17 * Author: spike * // * eclipse cdt, gcc 4.8.1 */# include
        
         
# Include
         
          
# Include
          
           
# Include
           
            
# Include
            
             
# Include using namespace std; class Program {static const int MAX_N = 100; int n = 3, W = 7; int w [MAX_N] = {3, 4, 2 }, v [MAX_N] = {4, 5, 3}; int dp [MAX_N + 1]; public: void solve () {memset (dp, 0, sizeof (dp )); for (int I = 0; I
             
              Output:
              

 

 

result = 10


 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.