尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
Backtracking
Sum of Subsets
and
Knapsack
Backtracking 2
Backtracking
• Two versions of backtracking algorithms
– Solution needs only to be feasible (satisfy
problem’s constraints)
• sum of subsets
– Solution needs also to be optimal
– knapsack
Backtracking 3
The backtracking method
• A given problem has a set of constraints and
possibly an objective function
• The solution optimizes an objective function,
and/or is feasible.
• We can represent the solution space for the
problem using a state space tree
– The root of the tree represents 0 choices,
– Nodes at depth 1 represent first choice
– Nodes at depth 2 represent the second choice,
etc.
– In this tree a path from a root to a leaf
represents a candidate solution
Backtracking 4
Sum of subsets
• Problem: Given n positive integers w1, ... wn and a
positive integer S. Find all subsets of w1, ... wn that
sum to S.
• Example:
n=3, S=6, and w1=2, w2=4, w3=6
• Solutions:
{2,4} and {6}
Backtracking 5
Sum of subsets
• We will assume a binary state space tree.
• The nodes at depth 1 are for including (yes, no)
item 1, the nodes at depth 2 are for item 2, etc.
• The left branch includes wi, and the right branch
excludes wi.
• The nodes contain the sum of the weights
included so far
Backtracking 6
Sum of subset Problem:
State SpaceTree for 3 items
w1 = 2, w2 = 4, w3 = 6 and S = 6
i1
i2
i3
yes no
0
0
0
0
2
2
2
6
612 8
4
410 6
yes
yes
no
no
no
nonono
The sum of the included integers is stored at the node.
yes
yes yesyes
Backtracking 7
A Depth First Search solution
• Problems can be solved using depth first search
of the (implicit) state space tree.
• Each node will save its depth and its (possibly
partial) current solution
• DFS can check whether node v is a leaf.
– If it is a leaf then check if the current solution
satisfies the constraints
– Code can be added to find the optimal solution
Backtracking 8
A DFS solution
• Such a DFS algorithm will be very slow.
• It does not check for every solution state (node)
whether a solution has been reached, or whether
a partial solution can lead to a feasible solution
• Is there a more efficient solution?
Backtracking 9
Backtracking
• Definition: We call a node nonpromising if it
cannot lead to a feasible (or optimal) solution,
otherwise it is promising
• Main idea: Backtracking consists of doing a
DFS of the state space tree, checking whether
each node is promising and if the node is
nonpromising backtracking to the node’s parent
Backtracking 10
Backtracking
• The state space tree consisting of expanded
nodes only is called the pruned state space tree
• The following slide shows the pruned state space
tree for the sum of subsets example
• There are only 15 nodes in the pruned state space
tree
• The full state space tree has 31 nodes
Backtracking 11
A Pruned State Space Tree (find all solutions)
w1 = 3, w2 = 4, w3 = 5, w4 = 6; S = 13
0
0
0
3
3
3
7
712 8
4
49
5
3
4 40
0
0
5 50 0 0
06
13 7
Sum of subsets problem
Backtracking 12
Backtracking algorithm
void checknode (node v) {
node u
if (promising ( v ))
if (aSolutionAt( v ))
write the solution
else //expand the node
for ( each child u of v )
checknode ( u )
Backtracking 13
Checknode
• Checknode uses the functions:
– promising(v) which checks that the partial solution
represented by v can lead to the required solution
– aSolutionAt(v) which checks whether the partial
solution represented by node v solves the
problem.
Backtracking 14
Sum of subsets – when is a node “promising”?
• Consider a node at depth i
• weightSoFar = weight of node, i.e., sum of numbers
included in partial solution node represents
• totalPossibleLeft = weight of the remaining items i+1
to n (for a node at depth i)
• A node at depth i is non-promising
if (weightSoFar + totalPossibleLeft < S )
or (weightSoFar + w[i+1] > S )
• To be able to use this “promising function” the wi
must be sorted in non-decreasing order
Backtracking 15
A Pruned State Space Tree
w1 = 3, w2 = 4, w3 = 5, w4 = 6; S = 13
0
0
0
3
3
3
7
712 8
4
49
5
3
4 40
0
0
5 50 0 0
06
13 7 - backtrack
1
2
3
4 5
6 7
8
109
11
12
15
14
13
Nodes numbered in “call” order
Backtracking 16
sumOfSubsets ( i, weightSoFar, totalPossibleLeft )
1) if (promising ( i )) //may lead to solution
2) then if ( weightSoFar == S )
3) then print include[ 1 ] to include[ i ] //found solution
4) else //expand the node when weightSoFar < S
5) include [ i + 1 ] = "yes” //try including
6) sumOfSubsets ( i + 1,
weightSoFar + w[i + 1],
totalPossibleLeft - w[i + 1] )
7) include [ i + 1 ] = "no” //try excluding
8) sumOfSubsets ( i + 1, weightSoFar ,
totalPossibleLeft - w[i + 1] )
boolean promising (i )
1) return ( weightSoFar + totalPossibleLeft ≥ S) &&
( weightSoFar == S || weightSoFar + w[i + 1] ≤ S )
Prints all solutions!
Initial call sumOfSubsets(0, 0, )∑=
n
i
iw
1
Backtracking 17
Backtracking for optimization problems
• To deal with optimization we compute:
best - value of best solution achieved so far
value(v) - the value of the solution at node v
– Modify promising(v)
• Best is initialized to a value that is equal to a candidate
solution or worse than any possible solution.
• Best is updated to value(v) if the solution at v is “better”
• By “better” we mean:
– larger in the case of maximization and
– smaller in the case of minimization
Backtracking 18
Modifying promising
• A node is promising when
– it is feasible and can lead to a feasible solution
and
– “there is a chance that a better solution than
best can be achieved by expanding it”
• Otherwise it is nonpromising
• A bound on the best solution that can be
achieved by expanding the node is computed and
compared to best
• If the bound > best for maximization, (< best for
minimization) the node is promising
How is
it determined?
Backtracking 19
Modifying promising for
Maximization Problems
• For a maximization problem the bound is an upper
bound,
– the largest possible solution that can be
achieved by expanding the node is less or
equal to the upper bound
• If upper bound > best so far, a better solution
may be found by expanding the node and the
feasible node is promising
Backtracking 20
Modifying promising for
Minimization Problems
• For minimization the bound is a lower bound,
– the smallest possible solution that can be
achieved by expanding the node is less or
equal to the lower bound
• If lower bound < best a better solution may be
found and the feasible node is promising
Backtracking 21
Template for backtracking in the case of
optimization problems.
Procedure checknode (node v ) {
node u ;
if ( value(v) is better than best )
best = value(v);
if (promising (v) )
for (each child u of v)
checknode (u );
}
• best is the best value so
far and is initialized to a
value that is equal or
worse than any possible
solution.
• value(v) is the value of
the solution at the node.
Backtracking 22
Notation for knapsack
• We use maxprofit to denote best
• profit(v) to denote value(v)
Backtracking 23
The state space tree for knapsack
• Each node v will include 3 values:
– profit (v) = sum of profits of all items included in
the knapsack (on a path from root to v)
– weight (v)= the sum of the weights of all items
included in the knapsack (on a path from root to v)
– upperBound(v). upperBound(v) is greater or equal
to the maximum benefit that can be found by
expanding the whole subtree of the state space
tree with root v.
• The nodes are numbered in the order of expansion
Backtracking 24
Promising nodes for 0/1 knapsack
• Node v is promising if weight(v) < C, and
upperBound(v)>maxprofit
• Otherwise it is not promising
• Note that when weight(v) = C, or maxprofit =
upperbound(v) the node is non promising
Backtracking 25
Main idea for upper bound
• Theorem: The optimal profit for 0/1 knapsack ≤
optimal profit for KWF
• Proof:
• Clearly the optimal solution to 0/1 knapsack is a
possible solution to KWF. So the optimal profit of KWF
is greater or equal to that of 0/1 knapsack
• Main idea: KWF can be used for computing the upper
bounds
Backtracking 26
Computing the upper bound for 0/1 knapsack
• Given node v at depth i.
• UpperBound(v) =
KWF2(i+1, weight(v), profit(v), w, p, C, n)
• KWF2 requires that the items be ordered by non
increasing pi / wi, so if we arrange the items in this
order before applying the backtracking algorithm,
KWF2 will pick the remaining items in the required
order.
Backtracking 27
KWF2(i, weight, profit, w, p, C, n)
1. bound = profit
2. for j=i to n
3. x[j]=0 //initialize variables to 0
4. while (weight<C)&& (i<=n) //not “full”and more items
5. if weight+w[i]<=C //room for next item
6. x[i]=1 //item i is added to knapsack
7. weight=weight+w[i]; bound = bound +p[i]
8. else
9. x[i]=(C-weight)/w[i] //fraction of i added to knapsack
10. weight=C; bound = bound + p[i]*x[i]
11. i=i+1 // next item
12. return bound
• KWF2 is in O(n) (assuming items sorted before applying
backtracking)
Backtracking 28
C++ version
• The arrays w, p, include and bestset have size
n+1.
• Location 0 is not used
• include contains the current solution
• bestset the best solution so far
Backtracking 29
Before calling Knapsack
numbest=0; //number of items considered
maxprofit=0;
knapsack(0,0,0);
cout << maxprofit;
for (i=1; i<= numbest; i++)
cout << bestset[i]; //the best solution
• maxprofit is initialized to $0, which is the worst profit
that can be achieved with positive pis
• In Knapsack - before determining if node v is
promising, maxprofit and bestset are updated
Backtracking 30
knapsack(i, profit, weight)
if ( weight <= C && profit > maxprofit)
// save better solution
maxprofit=profit //save new profit
numbest= i; bestset = include//save solution
if promising(i)
include [i + 1] = “ yes”
knapsack(i+1, profit+p[i+1], weight+ w[i+1])
include[i+1] = “no”
knapsack(i+1,profit,weight)
Backtracking 31
Promising(i)
promising(i)
//Cannot get a solution by expanding node
if weight >= C return false
//Compute upper bound
bound = KWF2(i+1, weight, profit, w, p, C, n)
return (bound>maxprofit)
Backtracking 32
Example from Neapolitan & Naimipour
• Suppose n = 4, W = 16, and we have the following:
i pi wi pi / wi
1 $40 2 $20
2 $30 5 $6
3 $50 10 $5
4 $10 5 $2
• Note the the items are in the correct order needed by
KWF
Backtracking 33
maxprofit = $0 (n = 4, C = 16 )
Node 1
a) profit = $ 0
weight = 0
b) bound = profit + p1 + p2 + (C - 7 ) * p3 / w3
= $0 + $40 + $30 + (16 -7) X $50/10 =$115
c) 1 is promising because its weight =0 < C = 16
and its bound $115 > 0 the value of maxprofit.
The calculation for node 1
Backtracking 34
Item 1 with profit $40 and weight 2 is included
maxprofit = $40
a) profit = $40
weight = 2
b) bound = profit + p2 + (C - 7) X p3 / w3
= $40 + $30 + (16 -7) X $50/10 =$115
c) 2 is promising because its weight =2 < C = 16
and its bound $115 > $40 the value of maxprofit.
The calculation for node 2
Backtracking 35
Item 1 with profit $40 and weight 2 is not included
At this point maxprofit=$90 and is not changed
a) profit = $0
weight = 0
b) bound = profit + p2 + p3+ (C - 15) X p4 / w4
= $0 + $30 +$50+ (16 -15) X $10/5 =$82
c) 13 is nonpromising because its bound $82 < $90
the value of maxprofit.
The calculation for node 13
Backtracking 36
1
13
$0
0
$115
$40
2
$115
$0
0
$82
Item 1 [$40, 2]
B
82<90Item 2 [$30, 5]
$70
7
$115
$120
17
2
3
4
F
17>16
Item 3 [$50, 10]
Item 4 [$10, 5]
$40
2
$98
8
$70
7
$80
5
$90
12
$98
9
$40
2
$50
12
B
50<90$80
12
$80
6
$70
7
$70
7
N N
$100
17
10 $90
12
$90
11
maxprofit = 90
profit
weight
bound
Example
F - not feasible
N - not optimal
B- cannot lead to
best solution
Optimal
maxprofit =0
maxprofit =40
maxprofit =70
maxprofit =80
F
17>16

More Related Content

What's hot

Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
Salah Amean
 
Lecture 16 memory bounded search
Lecture 16 memory bounded searchLecture 16 memory bounded search
Lecture 16 memory bounded search
Hema Kashyap
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
mandlapure
 
Lecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithmLecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithm
Hema Kashyap
 
Chapter 4 (final)
Chapter 4 (final)Chapter 4 (final)
Chapter 4 (final)
Nateshwar Kamlesh
 
Parametric & Non-Parametric Machine Learning (Supervised ML)
Parametric & Non-Parametric Machine Learning (Supervised ML)Parametric & Non-Parametric Machine Learning (Supervised ML)
Parametric & Non-Parametric Machine Learning (Supervised ML)
Rehan Guha
 
L03 ai - knowledge representation using logic
L03 ai - knowledge representation using logicL03 ai - knowledge representation using logic
L03 ai - knowledge representation using logic
Manjula V
 
Artificial Intelligence -- Search Algorithms
Artificial Intelligence-- Search Algorithms Artificial Intelligence-- Search Algorithms
Artificial Intelligence -- Search Algorithms
Syed Ahmed
 
04 reasoning systems
04 reasoning systems04 reasoning systems
04 reasoning systems
John Issac
 
Backtracking
BacktrackingBacktracking
Backtracking
Sally Salem
 
AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)
Tajim Md. Niamat Ullah Akhund
 
Adversarial Search
Adversarial SearchAdversarial Search
Adversarial Search
Megha Sharma
 
Introduction to Approximation Algorithms
Introduction to Approximation AlgorithmsIntroduction to Approximation Algorithms
Introduction to Approximation Algorithms
Jhoirene Clemente
 
Dempster Shafer Theory AI CSE 8th Sem
Dempster Shafer Theory AI CSE 8th SemDempster Shafer Theory AI CSE 8th Sem
Dempster Shafer Theory AI CSE 8th Sem
DigiGurukul
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structure
Vrushali Dhanokar
 
Expert system mycin
Expert system   mycinExpert system   mycin
Expert system mycin
university of education,Lahore
 
Water jug problem ai part 6
Water jug problem ai part 6Water jug problem ai part 6
Water jug problem ai part 6
Kirti Verma
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and Correlations
Justin Cletus
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 

What's hot (20)

Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
Data Mining: Concepts and Techniques chapter 07 : Advanced Frequent Pattern M...
 
Lecture 16 memory bounded search
Lecture 16 memory bounded searchLecture 16 memory bounded search
Lecture 16 memory bounded search
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Lecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithmLecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithm
 
Chapter 4 (final)
Chapter 4 (final)Chapter 4 (final)
Chapter 4 (final)
 
Parametric & Non-Parametric Machine Learning (Supervised ML)
Parametric & Non-Parametric Machine Learning (Supervised ML)Parametric & Non-Parametric Machine Learning (Supervised ML)
Parametric & Non-Parametric Machine Learning (Supervised ML)
 
L03 ai - knowledge representation using logic
L03 ai - knowledge representation using logicL03 ai - knowledge representation using logic
L03 ai - knowledge representation using logic
 
Artificial Intelligence -- Search Algorithms
Artificial Intelligence-- Search Algorithms Artificial Intelligence-- Search Algorithms
Artificial Intelligence -- Search Algorithms
 
04 reasoning systems
04 reasoning systems04 reasoning systems
04 reasoning systems
 
Backtracking
BacktrackingBacktracking
Backtracking
 
AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)
 
Adversarial Search
Adversarial SearchAdversarial Search
Adversarial Search
 
Introduction to Approximation Algorithms
Introduction to Approximation AlgorithmsIntroduction to Approximation Algorithms
Introduction to Approximation Algorithms
 
Dempster Shafer Theory AI CSE 8th Sem
Dempster Shafer Theory AI CSE 8th SemDempster Shafer Theory AI CSE 8th Sem
Dempster Shafer Theory AI CSE 8th Sem
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
 
Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structure
 
Expert system mycin
Expert system   mycinExpert system   mycin
Expert system mycin
 
Water jug problem ai part 6
Water jug problem ai part 6Water jug problem ai part 6
Water jug problem ai part 6
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and Correlations
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 

Viewers also liked

Backtracking
BacktrackingBacktracking
Backtracking
Sulman Bin Khurshid
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
Tech_MX
 
backtracking algorithms of ada
backtracking algorithms of adabacktracking algorithms of ada
backtracking algorithms of ada
Sahil Kumar
 
Queue- 8 Queen
Queue- 8 QueenQueue- 8 Queen
Queue- 8 Queen
Ha Ninh
 
Subset sum problem Dynamic and Brute Force Approch
Subset sum problem Dynamic and Brute Force ApprochSubset sum problem Dynamic and Brute Force Approch
Subset sum problem Dynamic and Brute Force Approch
Ijlal Ijlal
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
Krish_ver2
 
21 backtracking
21 backtracking21 backtracking
21 backtracking
Aparup Behera
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
Vikas Sharma
 
Graph coloring and_applications
Graph coloring and_applicationsGraph coloring and_applications
Graph coloring and_applications
mohammad alkhalil
 
GRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONSGRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONS
Manojit Chakraborty
 
Back tracking and branch and bound class 20
Back tracking and branch and bound class 20Back tracking and branch and bound class 20
Back tracking and branch and bound class 20
Kumar
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 
Backtracking
Backtracking  Backtracking
Backtracking
Vikas Sharma
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
Jenny Galino
 
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm
Graph Coloring : Greedy Algorithm & Welsh Powell AlgorithmGraph Coloring : Greedy Algorithm & Welsh Powell Algorithm
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm
Priyank Jain
 
Graph coloring
Graph coloringGraph coloring
Graph coloring
Rashika Ahuja
 
Interactive Voting - Estimation and Rounding
Interactive Voting  - Estimation and RoundingInteractive Voting  - Estimation and Rounding
Interactive Voting - Estimation and Rounding
Qwizdom UK
 
Physical Computing and IoT
Physical Computing and IoTPhysical Computing and IoT
Physical Computing and IoT
Eduardo Oliveira
 
Long division 2 digit no remainder
Long division 2 digit no remainderLong division 2 digit no remainder
Long division 2 digit no remainder
lorciga
 
Seminar report on android os
Seminar report on android osSeminar report on android os
Seminar report on android os
Appsthentic Technology
 

Viewers also liked (20)

Backtracking
BacktrackingBacktracking
Backtracking
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
backtracking algorithms of ada
backtracking algorithms of adabacktracking algorithms of ada
backtracking algorithms of ada
 
Queue- 8 Queen
Queue- 8 QueenQueue- 8 Queen
Queue- 8 Queen
 
Subset sum problem Dynamic and Brute Force Approch
Subset sum problem Dynamic and Brute Force ApprochSubset sum problem Dynamic and Brute Force Approch
Subset sum problem Dynamic and Brute Force Approch
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
 
21 backtracking
21 backtracking21 backtracking
21 backtracking
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Graph coloring and_applications
Graph coloring and_applicationsGraph coloring and_applications
Graph coloring and_applications
 
GRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONSGRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONS
 
Back tracking and branch and bound class 20
Back tracking and branch and bound class 20Back tracking and branch and bound class 20
Back tracking and branch and bound class 20
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Backtracking
Backtracking  Backtracking
Backtracking
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
 
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm
Graph Coloring : Greedy Algorithm & Welsh Powell AlgorithmGraph Coloring : Greedy Algorithm & Welsh Powell Algorithm
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm
 
Graph coloring
Graph coloringGraph coloring
Graph coloring
 
Interactive Voting - Estimation and Rounding
Interactive Voting  - Estimation and RoundingInteractive Voting  - Estimation and Rounding
Interactive Voting - Estimation and Rounding
 
Physical Computing and IoT
Physical Computing and IoTPhysical Computing and IoT
Physical Computing and IoT
 
Long division 2 digit no remainder
Long division 2 digit no remainderLong division 2 digit no remainder
Long division 2 digit no remainder
 
Seminar report on android os
Seminar report on android osSeminar report on android os
Seminar report on android os
 

Similar to Backtracking

fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.pptfdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
KartikGupta711
 
Optimization problems
Optimization problemsOptimization problems
Optimization problems
Ruchika Sinha
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
dakccse
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
BinayakMukherjee4
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Melaku Bayih Demessie
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
MaryJacob24
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
B.T.L.I.T
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
MaryJacob24
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
MaryJacob24
 
Sudoku
SudokuSudoku
Sudoku
Yara Ali
 
Support Vector Machines is the the the the the the the the the
Support Vector Machines is the the the the the the the the theSupport Vector Machines is the the the the the the the the the
Support Vector Machines is the the the the the the the the the
sanjaibalajeessn
 
Introduction to Optimization revised.ppt
Introduction to Optimization revised.pptIntroduction to Optimization revised.ppt
Introduction to Optimization revised.ppt
JahnaviGautam
 
5163147.ppt
5163147.ppt5163147.ppt
5163147.ppt
Mayurkumarpatil1
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdf
Shiwani Gupta
 
designanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptxdesignanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptx
arifimad15
 
super vector machines algorithms using deep
super vector machines algorithms using deepsuper vector machines algorithms using deep
super vector machines algorithms using deep
KNaveenKumarECE
 
Sudoku
SudokuSudoku
Machine learning interviews day2
Machine learning interviews   day2Machine learning interviews   day2
Machine learning interviews day2
rajmohanc
 
Adsa u2 ver 1.0.
Adsa u2 ver 1.0.Adsa u2 ver 1.0.
Adsa u2 ver 1.0.
Dr. C.V. Suresh Babu
 
course slides of Support-Vector-Machine.pdf
course slides of Support-Vector-Machine.pdfcourse slides of Support-Vector-Machine.pdf
course slides of Support-Vector-Machine.pdf
onurenginar1
 

Similar to Backtracking (20)

fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.pptfdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
 
Optimization problems
Optimization problemsOptimization problems
Optimization problems
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
 
Sudoku
SudokuSudoku
Sudoku
 
Support Vector Machines is the the the the the the the the the
Support Vector Machines is the the the the the the the the theSupport Vector Machines is the the the the the the the the the
Support Vector Machines is the the the the the the the the the
 
Introduction to Optimization revised.ppt
Introduction to Optimization revised.pptIntroduction to Optimization revised.ppt
Introduction to Optimization revised.ppt
 
5163147.ppt
5163147.ppt5163147.ppt
5163147.ppt
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdf
 
designanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptxdesignanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptx
 
super vector machines algorithms using deep
super vector machines algorithms using deepsuper vector machines algorithms using deep
super vector machines algorithms using deep
 
Sudoku
SudokuSudoku
Sudoku
 
Machine learning interviews day2
Machine learning interviews   day2Machine learning interviews   day2
Machine learning interviews day2
 
Adsa u2 ver 1.0.
Adsa u2 ver 1.0.Adsa u2 ver 1.0.
Adsa u2 ver 1.0.
 
course slides of Support-Vector-Machine.pdf
course slides of Support-Vector-Machine.pdfcourse slides of Support-Vector-Machine.pdf
course slides of Support-Vector-Machine.pdf
 

More from Vikas Sharma

Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
Vikas Sharma
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
Vikas Sharma
 
Coloring graphs
Coloring graphsColoring graphs
Coloring graphs
Vikas Sharma
 
Rules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaRules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharma
Vikas Sharma
 
Office automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaOffice automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharma
Vikas Sharma
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharma
Vikas Sharma
 
Website optimization by vikas sharma
Website optimization by vikas sharmaWebsite optimization by vikas sharma
Website optimization by vikas sharma
Vikas Sharma
 

More from Vikas Sharma (7)

Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Coloring graphs
Coloring graphsColoring graphs
Coloring graphs
 
Rules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaRules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharma
 
Office automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaOffice automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharma
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharma
 
Website optimization by vikas sharma
Website optimization by vikas sharmaWebsite optimization by vikas sharma
Website optimization by vikas sharma
 

Recently uploaded

220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology
Kalna College
 
220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science
Kalna College
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 
Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024
Friends of African Village Libraries
 
Non-Verbal Communication for Tech Professionals
Non-Verbal Communication for Tech ProfessionalsNon-Verbal Communication for Tech Professionals
Non-Verbal Communication for Tech Professionals
MattVassar1
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
khabri85
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
Infosec
 
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
biruktesfaye27
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
Sarojini38
 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
 
Decolonizing Universal Design for Learning
Decolonizing Universal Design for LearningDecolonizing Universal Design for Learning
Decolonizing Universal Design for Learning
Frederic Fovet
 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
chaudharyreet2244
 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
Celine George
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
RuchiRathor2
 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
PriyaKumari928991
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
MJDuyan
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
roshanranjit222
 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
nabaegha
 

Recently uploaded (20)

220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology
 
220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 
Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024
 
Non-Verbal Communication for Tech Professionals
Non-Verbal Communication for Tech ProfessionalsNon-Verbal Communication for Tech Professionals
Non-Verbal Communication for Tech Professionals
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
 
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
Ethiopia and Eritrea Eritrea's journey has been marked by resilience and dete...
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
 
Decolonizing Universal Design for Learning
Decolonizing Universal Design for LearningDecolonizing Universal Design for Learning
Decolonizing Universal Design for Learning
 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
 

Backtracking

  • 2. Backtracking 2 Backtracking • Two versions of backtracking algorithms – Solution needs only to be feasible (satisfy problem’s constraints) • sum of subsets – Solution needs also to be optimal – knapsack
  • 3. Backtracking 3 The backtracking method • A given problem has a set of constraints and possibly an objective function • The solution optimizes an objective function, and/or is feasible. • We can represent the solution space for the problem using a state space tree – The root of the tree represents 0 choices, – Nodes at depth 1 represent first choice – Nodes at depth 2 represent the second choice, etc. – In this tree a path from a root to a leaf represents a candidate solution
  • 4. Backtracking 4 Sum of subsets • Problem: Given n positive integers w1, ... wn and a positive integer S. Find all subsets of w1, ... wn that sum to S. • Example: n=3, S=6, and w1=2, w2=4, w3=6 • Solutions: {2,4} and {6}
  • 5. Backtracking 5 Sum of subsets • We will assume a binary state space tree. • The nodes at depth 1 are for including (yes, no) item 1, the nodes at depth 2 are for item 2, etc. • The left branch includes wi, and the right branch excludes wi. • The nodes contain the sum of the weights included so far
  • 6. Backtracking 6 Sum of subset Problem: State SpaceTree for 3 items w1 = 2, w2 = 4, w3 = 6 and S = 6 i1 i2 i3 yes no 0 0 0 0 2 2 2 6 612 8 4 410 6 yes yes no no no nonono The sum of the included integers is stored at the node. yes yes yesyes
  • 7. Backtracking 7 A Depth First Search solution • Problems can be solved using depth first search of the (implicit) state space tree. • Each node will save its depth and its (possibly partial) current solution • DFS can check whether node v is a leaf. – If it is a leaf then check if the current solution satisfies the constraints – Code can be added to find the optimal solution
  • 8. Backtracking 8 A DFS solution • Such a DFS algorithm will be very slow. • It does not check for every solution state (node) whether a solution has been reached, or whether a partial solution can lead to a feasible solution • Is there a more efficient solution?
  • 9. Backtracking 9 Backtracking • Definition: We call a node nonpromising if it cannot lead to a feasible (or optimal) solution, otherwise it is promising • Main idea: Backtracking consists of doing a DFS of the state space tree, checking whether each node is promising and if the node is nonpromising backtracking to the node’s parent
  • 10. Backtracking 10 Backtracking • The state space tree consisting of expanded nodes only is called the pruned state space tree • The following slide shows the pruned state space tree for the sum of subsets example • There are only 15 nodes in the pruned state space tree • The full state space tree has 31 nodes
  • 11. Backtracking 11 A Pruned State Space Tree (find all solutions) w1 = 3, w2 = 4, w3 = 5, w4 = 6; S = 13 0 0 0 3 3 3 7 712 8 4 49 5 3 4 40 0 0 5 50 0 0 06 13 7 Sum of subsets problem
  • 12. Backtracking 12 Backtracking algorithm void checknode (node v) { node u if (promising ( v )) if (aSolutionAt( v )) write the solution else //expand the node for ( each child u of v ) checknode ( u )
  • 13. Backtracking 13 Checknode • Checknode uses the functions: – promising(v) which checks that the partial solution represented by v can lead to the required solution – aSolutionAt(v) which checks whether the partial solution represented by node v solves the problem.
  • 14. Backtracking 14 Sum of subsets – when is a node “promising”? • Consider a node at depth i • weightSoFar = weight of node, i.e., sum of numbers included in partial solution node represents • totalPossibleLeft = weight of the remaining items i+1 to n (for a node at depth i) • A node at depth i is non-promising if (weightSoFar + totalPossibleLeft < S ) or (weightSoFar + w[i+1] > S ) • To be able to use this “promising function” the wi must be sorted in non-decreasing order
  • 15. Backtracking 15 A Pruned State Space Tree w1 = 3, w2 = 4, w3 = 5, w4 = 6; S = 13 0 0 0 3 3 3 7 712 8 4 49 5 3 4 40 0 0 5 50 0 0 06 13 7 - backtrack 1 2 3 4 5 6 7 8 109 11 12 15 14 13 Nodes numbered in “call” order
  • 16. Backtracking 16 sumOfSubsets ( i, weightSoFar, totalPossibleLeft ) 1) if (promising ( i )) //may lead to solution 2) then if ( weightSoFar == S ) 3) then print include[ 1 ] to include[ i ] //found solution 4) else //expand the node when weightSoFar < S 5) include [ i + 1 ] = "yes” //try including 6) sumOfSubsets ( i + 1, weightSoFar + w[i + 1], totalPossibleLeft - w[i + 1] ) 7) include [ i + 1 ] = "no” //try excluding 8) sumOfSubsets ( i + 1, weightSoFar , totalPossibleLeft - w[i + 1] ) boolean promising (i ) 1) return ( weightSoFar + totalPossibleLeft ≥ S) && ( weightSoFar == S || weightSoFar + w[i + 1] ≤ S ) Prints all solutions! Initial call sumOfSubsets(0, 0, )∑= n i iw 1
  • 17. Backtracking 17 Backtracking for optimization problems • To deal with optimization we compute: best - value of best solution achieved so far value(v) - the value of the solution at node v – Modify promising(v) • Best is initialized to a value that is equal to a candidate solution or worse than any possible solution. • Best is updated to value(v) if the solution at v is “better” • By “better” we mean: – larger in the case of maximization and – smaller in the case of minimization
  • 18. Backtracking 18 Modifying promising • A node is promising when – it is feasible and can lead to a feasible solution and – “there is a chance that a better solution than best can be achieved by expanding it” • Otherwise it is nonpromising • A bound on the best solution that can be achieved by expanding the node is computed and compared to best • If the bound > best for maximization, (< best for minimization) the node is promising How is it determined?
  • 19. Backtracking 19 Modifying promising for Maximization Problems • For a maximization problem the bound is an upper bound, – the largest possible solution that can be achieved by expanding the node is less or equal to the upper bound • If upper bound > best so far, a better solution may be found by expanding the node and the feasible node is promising
  • 20. Backtracking 20 Modifying promising for Minimization Problems • For minimization the bound is a lower bound, – the smallest possible solution that can be achieved by expanding the node is less or equal to the lower bound • If lower bound < best a better solution may be found and the feasible node is promising
  • 21. Backtracking 21 Template for backtracking in the case of optimization problems. Procedure checknode (node v ) { node u ; if ( value(v) is better than best ) best = value(v); if (promising (v) ) for (each child u of v) checknode (u ); } • best is the best value so far and is initialized to a value that is equal or worse than any possible solution. • value(v) is the value of the solution at the node.
  • 22. Backtracking 22 Notation for knapsack • We use maxprofit to denote best • profit(v) to denote value(v)
  • 23. Backtracking 23 The state space tree for knapsack • Each node v will include 3 values: – profit (v) = sum of profits of all items included in the knapsack (on a path from root to v) – weight (v)= the sum of the weights of all items included in the knapsack (on a path from root to v) – upperBound(v). upperBound(v) is greater or equal to the maximum benefit that can be found by expanding the whole subtree of the state space tree with root v. • The nodes are numbered in the order of expansion
  • 24. Backtracking 24 Promising nodes for 0/1 knapsack • Node v is promising if weight(v) < C, and upperBound(v)>maxprofit • Otherwise it is not promising • Note that when weight(v) = C, or maxprofit = upperbound(v) the node is non promising
  • 25. Backtracking 25 Main idea for upper bound • Theorem: The optimal profit for 0/1 knapsack ≤ optimal profit for KWF • Proof: • Clearly the optimal solution to 0/1 knapsack is a possible solution to KWF. So the optimal profit of KWF is greater or equal to that of 0/1 knapsack • Main idea: KWF can be used for computing the upper bounds
  • 26. Backtracking 26 Computing the upper bound for 0/1 knapsack • Given node v at depth i. • UpperBound(v) = KWF2(i+1, weight(v), profit(v), w, p, C, n) • KWF2 requires that the items be ordered by non increasing pi / wi, so if we arrange the items in this order before applying the backtracking algorithm, KWF2 will pick the remaining items in the required order.
  • 27. Backtracking 27 KWF2(i, weight, profit, w, p, C, n) 1. bound = profit 2. for j=i to n 3. x[j]=0 //initialize variables to 0 4. while (weight<C)&& (i<=n) //not “full”and more items 5. if weight+w[i]<=C //room for next item 6. x[i]=1 //item i is added to knapsack 7. weight=weight+w[i]; bound = bound +p[i] 8. else 9. x[i]=(C-weight)/w[i] //fraction of i added to knapsack 10. weight=C; bound = bound + p[i]*x[i] 11. i=i+1 // next item 12. return bound • KWF2 is in O(n) (assuming items sorted before applying backtracking)
  • 28. Backtracking 28 C++ version • The arrays w, p, include and bestset have size n+1. • Location 0 is not used • include contains the current solution • bestset the best solution so far
  • 29. Backtracking 29 Before calling Knapsack numbest=0; //number of items considered maxprofit=0; knapsack(0,0,0); cout << maxprofit; for (i=1; i<= numbest; i++) cout << bestset[i]; //the best solution • maxprofit is initialized to $0, which is the worst profit that can be achieved with positive pis • In Knapsack - before determining if node v is promising, maxprofit and bestset are updated
  • 30. Backtracking 30 knapsack(i, profit, weight) if ( weight <= C && profit > maxprofit) // save better solution maxprofit=profit //save new profit numbest= i; bestset = include//save solution if promising(i) include [i + 1] = “ yes” knapsack(i+1, profit+p[i+1], weight+ w[i+1]) include[i+1] = “no” knapsack(i+1,profit,weight)
  • 31. Backtracking 31 Promising(i) promising(i) //Cannot get a solution by expanding node if weight >= C return false //Compute upper bound bound = KWF2(i+1, weight, profit, w, p, C, n) return (bound>maxprofit)
  • 32. Backtracking 32 Example from Neapolitan & Naimipour • Suppose n = 4, W = 16, and we have the following: i pi wi pi / wi 1 $40 2 $20 2 $30 5 $6 3 $50 10 $5 4 $10 5 $2 • Note the the items are in the correct order needed by KWF
  • 33. Backtracking 33 maxprofit = $0 (n = 4, C = 16 ) Node 1 a) profit = $ 0 weight = 0 b) bound = profit + p1 + p2 + (C - 7 ) * p3 / w3 = $0 + $40 + $30 + (16 -7) X $50/10 =$115 c) 1 is promising because its weight =0 < C = 16 and its bound $115 > 0 the value of maxprofit. The calculation for node 1
  • 34. Backtracking 34 Item 1 with profit $40 and weight 2 is included maxprofit = $40 a) profit = $40 weight = 2 b) bound = profit + p2 + (C - 7) X p3 / w3 = $40 + $30 + (16 -7) X $50/10 =$115 c) 2 is promising because its weight =2 < C = 16 and its bound $115 > $40 the value of maxprofit. The calculation for node 2
  • 35. Backtracking 35 Item 1 with profit $40 and weight 2 is not included At this point maxprofit=$90 and is not changed a) profit = $0 weight = 0 b) bound = profit + p2 + p3+ (C - 15) X p4 / w4 = $0 + $30 +$50+ (16 -15) X $10/5 =$82 c) 13 is nonpromising because its bound $82 < $90 the value of maxprofit. The calculation for node 13
  • 36. Backtracking 36 1 13 $0 0 $115 $40 2 $115 $0 0 $82 Item 1 [$40, 2] B 82<90Item 2 [$30, 5] $70 7 $115 $120 17 2 3 4 F 17>16 Item 3 [$50, 10] Item 4 [$10, 5] $40 2 $98 8 $70 7 $80 5 $90 12 $98 9 $40 2 $50 12 B 50<90$80 12 $80 6 $70 7 $70 7 N N $100 17 10 $90 12 $90 11 maxprofit = 90 profit weight bound Example F - not feasible N - not optimal B- cannot lead to best solution Optimal maxprofit =0 maxprofit =40 maxprofit =70 maxprofit =80 F 17>16
  翻译: