Programming Algorithm-Knapsack Problem (three types of Dynamic Planning) code (C)

Source: Internet
Author: User

Programming Algorithm-Knapsack Problem (three types of Dynamic Planning) code (C)
Knapsack Problem (three dynamic plans) code (C)

 

 

 

AvailableDynamic Programming (DP)You can useMemory-based searchPush and export the recursive formula, which can be usedThree different directionsSolve the problem.

Dynamic Planning mainly involvesStatus TransferTo be clear.

 

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]; // The default value is 0 public: void solve () {for (int I = n-1; I> = 0; I --) {for (int j = 0; j <= W; ++ j) {if (j
      
       Output:
       

 

 

result = 7

 

Space-saving and usable1-dimensional arrayDynamic Planning.

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] = {2,1,3,2}, v[MAX_N]={3,2,4,2};int dp[MAX_N+1];public:void solve() {memset(dp, 0, sizeof(dp));for (int i=0; i
             
              =w[i]; --j) {dp[j] = max(dp[j], dp[j-w[i]]+v[i]);}}printf(result = %d, dp[W]);}};int main(void){Program P;P.solve(); return 0;}
             
            
           
          
         
        

Output:

 

 

result = 7


 

 

 

 

 

 

 

 

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.