Retrospective solution of 0-1 knapsack problem (Wang Xiaodong of the law problem)

Source: Internet
Author: User

Given n kinds of goods and a backpack. The weight of item I is WI, its value is VI, the capacity of the backpack is C. Q. How do you choose which items are loaded into your backpack so that the total value of the items loaded into your backpack is greatest ?

The entire solution of the space equivalent of a binary tree, the left is 0, the representative does not take this item, the right is 1, the representative take this item, and then DFS, backtracking when modified.

Note that there should be two pruning here, and I only wrote one here.

#include <iostream> #include <string> #include <cstring>using namespace Std;int n,totcap,bestval;// Number of items, backpack capacity, maximum value const int N=1000;int val[n],w[n],x[n],bestx[n];//Item value, weight of item, X[i] selection of temporary items, item selection void Dfs (int i,            int Cv,int cw) {//CW Current in-package item weight, CV current in-Package item value if (I&GT;N)//End {if (cv>bestval) {BESTVAL=CV;        for (i=1;i<=n;i++) bestx[i]=x[i]; }} else for (int j=0;j<=1;j++) {x[i]=j;//takes or does not take if (CW+X[I]*W[I]&LT;=TOTCA                p) {Cw+=w[i]*x[i];                Cv+=val[i]*x[i];                DFS (I+1,CV,CW);                Cw-=w[i]*x[i];            Cv-=val[i]*x[i];    }}}int Main () {int i;     bestval=0;    cout<< "Please enter the maximum capacity of the backpack:" <<endl;;    cin>>totcap;    cout<< "Please enter the number of items:" <<endl;    cin>>n;    cout<< "Please enter the weight of the item in turn:" <<endl;    for (i=1;i<=n;i++) cin>>w[i]; cout<< "Please enter the value of the item in turn:" <<endL    for (i=1;i<=n;i++) cin>>val[i];    DFS (1,0,0);    cout<< "Maximum value:" <<endl;    cout<<bestval<<endl;    cout<< "The label of the selected item is:" <<endl;    for (i=1;i<=n;i++) if (bestx[i]==1) cout<<i<< "";    cout<<endl; return 0;}


Retrospective solution of 0-1 knapsack problem (Wang Xiaodong of the law 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.