Dynamic planning Three: 0-1 knapsack problem

Source: Internet
Author: User

1. Description of the problem:

A certain object and a backpack, the weight of the object I is the value of the WI for the VI, the capacity of the backpack is C, how to put the maximum value of the backpack? The problem can be described as:

  

  

2. Problem Analysis:

1) Optimal sub-structure:

  

where J=c-wiyi

2) Recursive relationship: Set the optimal value of M (I,j), J for the optimal capacity, I for optional items, by the optimal substructure properties can be established recursive:

  

  

3. Algorithm Description:(not optimized)

1#include <iostream>2 using namespacestd;3 intc[Ten][ -];4 intKnap (intMintN) {5     intw[Ten];6     intv[Ten];7cout <<"input Object Weight W and value v:\n";8      for(inti =1; I <= N; i++){9CIN >> W[i] >>V[i];Ten     } One      for(inti =1; I <= N; i++) A     { -          for(intj =1; J <= M; J + +)//the capacity of the backpack is tested individually -         { the             if(W[i] <=j) -             { -                 if(C[i-1][J] < V[i] + c[i-1][j-W[i]]) -C[I][J] = V[i] + c[i-1][j-W[i]]; +                 Else -C[I][J] = c[i-1][j]; +             } A             Else atC[I][J] = c[i-1][j]; -         } -     } -     returnC[n][m]; - } -  in intMain () { -     intN, M; tocout <<"number of input objects N and backpack capacity m:\n"; +CIN >> N >>m; -cout << Knap (n, m) <<Endl; the      for(inti =0; I <= N; i++) *     { $          for(intj =0; J <= M; J + +)Panax Notoginsengcout<<C[i][j]; -cout<<Endl; the     } +     return 0; A}

  

Dynamic planning Three: 0-1 knapsack problem

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.