Using backtracking method to solve 0-1 knapsack problem

Source: Internet
Author: User
Using backtracking to solve 0-1 knapsack problem needs to solve the problem:
1. How to generate a subset tree dynamically
2. How to design node types in a subset tree
3. How to design Two pruning functions: constraint function and bounding function
4. How to save one or more optimal solutions while preserving the optimal value

Workaround:
1. The subset tree is generated dynamically, the node type in the subset tree is shared with the object type, and the parent-child relationship between nodes is associated by recursive invocation, which does not set the variable display representation in the class.
2. In order to facilitate the calculation of the gauge function and the use of the program, first of all the items pretreatment, the unit value of the items in descending order of weight.

3. Set up the program running a structure of the optimal solution variable, the corresponding optimal value and the current optimal solution for the optimal value comparison, if better than the current optimal solution, will cover the current optimal solution, if the corresponding value of the current optimal solution is equal, then save two optimal solutions.


The following are the specific source code:

#include "stdafx.h" #include <iostream> using namespace std;
typedef int TYPEW;

typedef int TYPEP;
	Class object{friend class Knap Public:int operator <= (object a) const{return (d >= A.D); } Private:int ID; Item number Typew W; Goods weight TYPEP p; Item value float D;

Unit weight Value};
      0-1 knapsack problem Main classes class knap{Public:knap (Typew *w, Typep *p, Typew c, int n);
	&NBSP;TYPEP knapsack ()//backtracking method solves 0-1 knapsack problem by main function/backtracking method to solve 01 knapsack problem void BackTrack (int floor);
Responsible for printing the optimal value and the optimal solution, printing the result void print () in the order of the item number;
	Private://Compute node value upper bound Typep Bound (int i); Typew C; backpack capacity int n; Total Items Object *q; Items stored in the Q array are sorted in descending order of unit weight value Typew CW; Current pack weight TYPEP CP; Current package value int *cbestx; The current optimal solution int count; Number of optimal solutions int *bestx[10];	
	The optimal solution, the number of the optimal solution is not more than 10. Typep BESTP; Optimal value Typep OLDBESTP;

Used for backtracking boundary processing, save the last optimal value};
	Knap::knap (Typew *w, Typep *p, Typew c, int n) {//initialize Typew w = 0;
	Typep P = 0;
	Count = 0;
	This->c = C;
	OLDBESTP = 0;
	This->n = n;
	CW = 0;
	CP = 0;
	Q = new Object[n]; for (inti = 0; i<n;
		i++) {q[i].id = i+1;
 		Q[I].D = 1.0*p[i]/w[i];
		Q[I].W = W[i];
		Q[I].P = P[i];
		P + + p[i];
	W + + w[i];
		///The total weight of all items is less than or equal to the backpack capacity C if (W <= c) {bestp = P;
		int *newbestx = new Int[n];
		for (int i =0; i<n; i++) {newbestx[i] = 1;
		
	} bestx[count++] = NEWBESTX; ///The total weight of all items is greater than the backpack capacity C, the existence of the best package scheme//A simple bubble sort for (int i = 0; i<n-1; i++) for (int j = 0; j<n-i-1; j +) {if (q[j).
				D < q[j+1].d) {Object temp = q[j];
				Q[J] = q[j+1];
			Q[J+1] = temp;
		}} Typep Knap::knapsack () {if (Count > 0)//backpack capacity is large enough to load all items into the backpack {print () at initialization time;
	return BESTP;
		else//backpack capacity is less than all weight of the item, there is an optimal package scheme {CBESTX = new int[n]; BackTrack (0); From the array q subscript 0, the first node begins backtracking to solve} void Knap::backtrack (int floor) {if (Floor > N-1)//has been to the leaf node in the subset tree {if (cp = = Oldbest
			p)//Description There may be multiple optimal solutions {int *newbe = new Int[n];
			for (int i = 0; i < n; i++) {newbe[i] = Cbestx[i];
		} bestx[count++] = Newbe; } if (cp > OLDBESTP)//Description optimalThe solution needs to be updated with only one {count = 0;
			int *newbe = new Int[n];
			for (int i = 0; i < n; i++) {newbe[i] = Cbestx[i];
			} bestx[count++] = Newbe;
		OLDBESTP = CP;
			else {//Select an object with an array Q subscript floor to meet the knapsack capacity constraint if (c >= CW + Q[FLOOR].W) {cw = Q[FLOOR].W;
			CP = Q[FLOOR].P;
			if (CP >= BESTP) BESTP = CP;
			Cbestx[floor] = 1;
			BackTrack (floor + 1);
			CW-= Q[FLOOR].W;
		CP-= Q[FLOOR].P;
			}//shed the array Q subscript as floor items, satisfying the gauge function if (CP + Bound (floor + 1) >= BESTP) {Cbestx[floor] = 0;
		BackTrack (floor + 1);
	}} void Knap::p rint () {Typep *original = new Int[n+1];
	cout<< "a solution to each of the following behaviors:" <<endl;
		for (int i = count-1 i >= 0; i--) {for (int j = 0; J < N; j +) {Original[q[j].id] = bestx[i][j];
		for (int k = 1; k <= N; k++) {cout<< original[k] << "";
	} cout<<endl;
	} cout<< "The number of optimal solutions:" <<count<<endl;

cout<< "Best Value:" <<bestp<<endl; } typep knap::bound (int i) {Typew cleft = C-CW;
	Typep B = cp;
		while (I < n && q[i].w <= cleft) {cleft-= Q[I].W;
		B + + q[i].p;
	i++;
	if (i < n) b + = Q[I].P/Q[I].W * cleft;
return b;
	int _tmain (int argc, _tchar* argv[]) {const int N = 4;
	Typew C = 7;
	Typew W[n] = {2,3,5,2};
	Typep P[n] = {6,4,8,4};
	cout<< "Backpack Capacity:" <<c << ", Total items:" << n<<endl;
	cout<< "Object weight array:";
	for (int i = 0; i < N; i++) {cout<<w[i]<< "";
	} cout<<endl;
	cout<< "Object value array:";
	for (int i = 0; i < N; i++) {cout<<p[i]<< "";
	} cout<<endl;
	Knap K (W, p, C, N);
	K.knapsack ();
	K.print ();
	System ("pause");
return 0; }
The results of the operation are shown below:


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.