Backtracking Method-01 one of the problems with a backpack: recursive Mode

Source: Internet
Author: User

I. Backtracking

Backtracking is a systematic and leaping search algorithm. It searches for the solution space tree from the root node based on the depth-first policy in the solution space tree that contains all solutions to the problem. When an algorithm searches for any node of the spatial tree, it always determines whether the node certainly does not include the solution of the problem. If it is not included, the system searches for the subtree with the node as the root and traces back to the original node layer by layer. Otherwise, go to the subtree and continue searching based on the depth-first policy.

Using the Backtracking Method to Solve the problem usually involves the following three steps:

· Define the solution space for the given problem;

· Determine a space structure that is easy to search;

· Search space in depth-first mode, and use the pruning function during the search process to avoid invalid search;


Ii. 01 backpack Problem Description

01 A backpack problem is that an item is loaded into a backpack with a capacity of M, either put or not put. Select the items from n items that are loaded into the backpack. The weight and value of item I are Wi and Pi. Optimal Loading refers to the maximum value of the loaded item, that is, Sigma PiXi (I = 1 .. n. The constraint is Σ WiXi ≤ M and Xi ε [0, 1] (1 ≤ I ≤ n ).

In this expression, the value of Xi is required. Xi = 1 indicates that item I is loaded into a backpack, and Xi = 0 indicates that item I is not loaded into a backpack.

· That is, the constraints for determining feasible solutions are: Σ WiXi ≤ M (I = 0 .. n), Wi> 0, xiε [0, 1] (1 ≤ I ≤ n)

· Maximum target value: max Σ PiXi (I = 0 .. N-1), Pi> 0, Xi = 0 or 1 (0 ≤ I

0/1 the knapsack problem is a self-selection problem. It is suitable to use a subset tree to represent the space for solving the 0/1 knapsack problem. When searching for a spatial tree, as long as the left son node is a feasible node, the search enters the left child tree. The right child tree may contain the optimal solution before entering the right child tree search, otherwise, cut the right subtree.


Iii. pruning Functions

Set the total value of the remaining items to r, the value of x at the current node to cp, and the function value of the upper bound of the current x node to bp. L it is the maximum benefit of the currently searched answer node when cp + r = bp

The upper limit of the right subtree is calculated by sorting the remaining items by unit weight value, placing the items at a time until the items cannot be loaded, and then loading some unloaded items until they are filled with backpacks, the resulting value is the upper bound of the right subtree solution.

Iv. Recursive Implementation

Figure 1 shows the Recursive Implementation of the 01 backpack problem. Figure 2 shows the flowchart of the Recursive Implementation of the 01 backpack problem and describes the code implementation solution.


Figure 1 01 knapsack problem recursive description Fig 2 01 knapsack problem Recursive Implementation Flowchart


Figure 1 is easy to understand, and whether an item has been taken, that is, I

5. Recursive code implementation


Code 1 Main function test code:

public static void Main (string[] args){            Obj[] objs = new Obj[4];            objs[0] = new Obj() { Weight = 7, Price = 42 };            objs[1] = new Obj() { Weight = 3, Price = 12 };            objs[2] = new Obj() { Weight = 4, Price = 40 };            objs[3] = new Obj() { Weight = 5, Price = 25 };            Backtracking_Recursion1 r = new Backtracking_Recursion1();            r.W = 10;            r.objs = objs;            r.Backtracking(0);            Console.Read();}

Code 2Obj item code

Public class Obj {////// Item weight ///Public int Weight {get; set ;}////// Item value ///Public int Price {get; set ;}////// Whether the item is included in the package ///Internal bool Selected {get; set ;}}


Code 3 Recursive Implementation 01 knapsack problems

Class Backtracking_Recursion1 {# region field protected int m_currentWeight = 0; protected int m_currentPrice = 0; # endregion # region property ////// Backpack capacity //////
 
  
The default value is 20.
 Public int W {get; set;} public int n {get {return objs = null? 0: objs. Length ;}}////// Item, including weight/value and quantity //////
 
  
The objects.
 Public Obj [] objs {get; set ;}# endregion public void Backtracking (int I) {if (I >=n) {Printing (); return ;} if (objs [I]. weight + m_currentWeight <= W) {m_currentWeight + = objs [I]. weight; m_currentPrice + = objs [I]. price; objs [I]. selected = true; Backtracking (I + 1); m_currentPrice-= objs [I]. price; m_currentWeight-= objs [I]. weight;} objs [I]. selected = false; Backtracking (I + 1 );}////// Output path ///Protected void Printing () {Console. write ("<"); for (int I = 0; I <objs. length; I ++) {Console. write (objs [I]. selected? "1": "0");} Console. WriteLine (">, price:" + m_currentPrice.ToString () + "\ t weight:" + m_currentWeight.ToString ());}}



Six running results


Note:

1 In Code 3, the Printing () function can be called to determine and record the optimal path;

2. The following describes the sequential execution method of the backtracing method for a backpack problem, and two different implementation schemes are integrated through the template mode.


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.