Algorithm Design and Performance Analysis
Algorithm Design and Performance Analysis
(Autonomous)
Dundigal, Hyderabad -500 043
Information Technology
Prepared By
Dr. K Rajendra Prasad
Dr. R Obulakonda Reddy
Dr. G Ramu
Dr. B V Rao
Mr. Ch Suresh Kumar Raju
Ms. K Radhika
ALGORITHMS
Algorithm Definition
Formal Definition
An Algorithm is a finite set of instructions that, if followed,
accomplishes a particular task. In addition, all algorithms should satisfy
the following criteria.
One step is a key word, other Step is used for increment or decrement
ALGORITHM SPECIFICATION
repeat-until:
repeat{
<statement-1>
.
.
<statement-n>
}until<condition>
ALGORITHM SPECIFICATION
8. A conditional statement has the following forms.
(1) If <condition> then <statement>
(2) If <condition> then <statement-1>
Else <statement-2>
Case statement:
Case
{ :<condition-1>:<statement-1>
.
.
:<condition-n>:<statement-n>
:else:<statement-n+1>
}
ALGORITHM SPECIFICATION
9. Input and output are done using the instructions read & write.
SP(I)=0
Hence S(P)=Constant
EXAMPLE 2
Algorithm 2: Iterative function for sum a list of
numbers
Algorithm sum( list[ ], n)
{
tempsum = 0;
for i = 0 ton do
tempsum += list [i];
return tempsum;
}
}
In the above example the recursion stack space includes space for
formal parameters local variables and return address. Each call to rsum
requires 3 locations i.e. for list[ ],n and return address .As the length of
recursion is n+1.
S(P)>=3(n+1)
Time Complexity
Time Complexity
The time complexity of an algorithm is the amount of computer
time it needs to run to completion.
The time T(P) taken by a program P is the sum of the compile time
and the run (or execution)time. The compile time does not
depend on the instance characteristics.
T(P)=C+TP(I)
It is combination of
-Compile time (C) independent of instance characteristics
-Run (execution) time TP dependent of instance characteristics
}
T(n)=2n+2
EXAMPLE 3
Algorithm 3: Matrix addition
Algorithm add( a[ ][MAX_SIZE], b[ ][MAX_SIZE],
c[ ][MAX_SIZE], rows, cols )
{
for i := 1 to rows do {
count++; /* for i for loop */
for j := 1 to cols do {
count++; /* for j for loop */
c[i][j] := a[i][j] + b[i][j];
count++; /* for assignment statement */
}
count++; /* last time of j for loop */
}
count++; /* last time of i for loop */
}
T(n)=2rows*cols+2*rows+1
Time complexity
Computing Time Complexity
Tabular method for computing Time Complexity :
Algorithmrsum( list[ ], n) 0 - - 0 0
{ 0 - - 0 0
If (n<=0) then 1 1 1 1 1
return 0.0; 1 1 0 1 0
else 0 0 0 0 0
return rsum(list, n-1) + list[n];
1+x 0 1 0 1+x
} 0 0 0 0 0
Total 2 2+x
Example 3: Matrix addition
Statement s/e Frequency Total steps
Algorithm add(a,b,c,m,n) 0 - 0
{ 0 - 0
for i:=1 to m do 1 m+1 m+1
for j:=1 to n do 1 m(n+1) mn+m
c[i,j]:=a[i,j]+b[i,j]; 1 mn mn
} 0 - 0
Total 2mn+2m+1
Time complexity Analysis
Time complexity Analysis
•The worst-case complexity of the algorithm is the function
defined by the maximum number of steps taken on any instance of
size n. It represents the curve passing through the highest point of
each column.
Ο Notation
Ω Notation
θ Notation
Big oh notation: O
Definition
The function f(n)=O(g(n)) (read as “f of n is big oh of g of n”) iff
there exist positive constants c and n0 such that
f(n)≤C*g(n) for all n, n≥0
The value g(n)is the upper bound value of f(n).
Example:
Consider the following f(n) and g(n)...
f(n) = 3n + 2
g(n) = n
If we want to represent f(n) as O(g(n)) then it must satisfy
f(n) <= C x g(n) for all values of C > 0 and n0>= 1
f(n) <= C g(n)
⇒3n + 2 <= C n
Example:
3n+2=o(n2) as
Lim ((3n+2)/n2)=0
n∞
EXAMPLES
void printAllItemsTwice(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d\n", arr[i]);
}
for (int i = 0; i < size; i++)
{
printf("%d\n", arr[i]);
}
}
• If the sub problems are still relatively large, then the divide-and-
conquer strategy can possibly be reapplied. Often the sub
problems resulting from a divide-and-conquer design are of the
same type as the original problem.
DIVIDE AND CONQUER
• DAndC(Algorithm) is initially invoked as DandC(P), where ‘p’ is
the problem to be solved.
Where T(n) is the time for DAndC on any i/p of size ‘n’.
g(n) is the time of compute the answer directly for small
i/ps.
f(n) is the time for dividing P & combining the solution to
sub problems.
Control Abstract
Algorithm DAndC(P)
{
if small(P) then return S(P);
else
{
divide P into smaller instances
P1, P2… Pk, k>=1;
Apply DAndC to each of these sub problems;
return combine (DAndC(P1), DAndC(P2),…….,DAndC(Pk));
}
}
DIVIDE AND CONQUER
The complexity of many divide-and-conquer algorithms is given
by recurrence relation of the form
Binary search
Quick sort
Merge sort
Strassen’s matrix multiplication.
BINARY SEARCH
• Given a list of n elements arranged in increasing order.
-15,-6,0,7,9,23,54,82,101,112,125,131,142,151.
X=151
Found
Example
Array Elements
-15,-6,0,7,9,23,54,82,101,112,125,131,142,151.
x=-14
-15,-6,0,7,9,23,54,82,101,112,125,131,142,151.
x=9
Found
Time Complexity of binary search
The complexity of binary search is successful searches is
Algorithm INTERCHANGE(a, i, j)
{
p:= a[i];
a[i]:=a[j];
a[j]:=p;
}
Example
40 20 10 80 60 50 7 30 100
Partitioning Array
Given a pivot, partition the elements of the array such that
the resulting array consists of:
1. One sub-array that contains elements >= pivot
2. Another sub-array that contains elements < pivot
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i] <= a[pivot]
++ i
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i] <= a[pivot]
++ i
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i ]<= a[pivot]
++ i
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ] > a[pivot]
-- j
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
5. Swap a[ j ]and a[pivot_index]
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
1. While a[ i ]<= a[pivot]
++ i
2. While a[ j ]> a[pivot]
-- j
3. If i< j
swap a[ i ]and a[ j ]
4. While j > i, go to 1.
5. Swap a[ j ]and a[pivot_index]
pivot_index = 4 7 20 10 30 40 50 60 80 100
i j
Partition Result
7 20 10 30 40 50 60 80 100
T (n – 1) = T (n – 2) + C (n –1)
T (n – 2) = T (n – 3) + C (n –2)
- - - - - - --
T (2) = T (1) + C(2)
Adding up all these equations yields
T (n) =O(n2) - (3)
Analysis of Quick Sort
Best Case Analysis
Finally,
Which yields,
. .
. .
T(3)/4 = 2/4 +T(2)/3
T(2)/3 = 2/3 + T(1)/2 T(1)/2 = 2/2 +T(0)
Analysis of Quick Sort
Adding both sides:
T(n)/(n+1) + [T(n-1)/n + T(n-2)/(n-1) + ------------- + T(2)/3
+T(1)/2]
= [T(n-1)/n + T(n-2)/(n-1) + ------------- + T(2)/3 + T(1)/2] +
T(0)+ [2/(n+1) + 2/n + 2/(n-1) + ---------- +2/4 +2/3]
}
MERGE SORT
Algorithm MERGE (low, mid,high)
// a (low : high) is a global array containing two sortedsubsets
// in a (low : mid) and in a (mid + 1 :high).
// The objective is to merge these sorted sets into singlesorted
// set residing in a (low : high). An auxiliary array B isused.
{
h :=low; i := low; j:= mid + 1;
while ((h <mid) and (J <high))do
{
if (a[h] <a[j])then
{
b[i] :=a[h]; h:=h+1;
}
else
{
MERGE SORT
b[i] :=a[j]; j := j +1;
}
i := i +1;
}// while
if (h > mid) then
for k := j to high do
{
b[i] := a[k]; i := i +1
}
for k := h to mid do
{
b[i] := a[K]; i := i +l;
}
for k := low to high do
a[k] :=b[k]; } //end MERGE
Example 1
Analysis of Merge Sort
Example 2
Analysis of Merge Sort
• We will assume that ‘n’ is a power of 2, so that we always split
into even halves, so we solve for the case n =2k.
The problem:
A B C
nn n n n n
131
n
The traditional way:
C ij A ik B kj
k 1
T (n) O (n )
3
C 11 A 11 B 11 A 12 B 21
C 12 A 11 B 12 A 12 B 22
C 21 A 21 B 11 A 22 B 21
C 22 A 21 B 12 A 22 B 22
133
n
T (n) 8 T ( ) an
2
2
O (n )
3
134
Example: use Divide-and-Conquer way to solve it as following:
1 1 1 1 1 1 1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 1 1 1
1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 0 1 1 3 3
C 11
1 1 1 1 1 0 0 0 3 3
1 1 1 0 1 0 1 0 3 0
C 12
1 1 1 0 1 0 0 0 3 0
1 1 1 1 1 0 1 1 3 3
C 21
0 0 1 1 0 0 0 0 0 0
1 1 1 0 1 0 1 0 3 0
C 22
0 0 1 0 0 0 0 0 0 0
135
Strassen’s Matrix Multiplication
Strassens introduces new way of computing the Cij’s using 7
multiplications and 18 additions or subtractions
P ( A 11 A 22 )( B 11 B 22 )
Q ( A 21 A 22 ) B 11
R A 11 ( B 12 B 22 )
S A 22 ( B 21 B 11 )
T ( A 11 A 12 ) B 22
U ( A 21 A 11 )( B 11 B 12 )
V ( A 12 A 22 )( B 21 B 22 )
C 11 P S T V
C 12 R T
C 21 Q S
C 22 P R Q U
136
Analysis
n
7 T ( ) an n 2
2
T (n) 2
b n 2
n 2
T (n) 7 T ( ) an
2
2 n 7 2 2
7 T ( ) ( ) an an
2
2 4
3 n 7 2 2 7 2 2
7 T ( ) ( ) an ( ) an an
3
2 4 4
137
Analysis
Assume n = 2k for some integer k
k 1 n 7 k2
7 T ( ) an ( ) 1
2
k 1
2 4
7 k 1
( ) 1
k 1 4
7 b an
2
7
1
4
7
b 7 cn (
k 2 k
)
4
7
7 Lg
b 7 cn ( b 7 cn
Lgn 2 Lgn Lgn 2 4
) (n )
4
bn cn (b c ) n
Lg 7 Lg 7 Lg 7
O (n ) O (n
Lg 7 2 . 81
)
138
Strassen’s Matrix Multiplication
Strassen’s Matrix Multiplication
•The matrix multiplication of algorithm due to Strassens is the
most dramatic example of divide and conquer technique (1969).
The problem:
A B C
nn n n n n
141
n
The traditional way:
C ij A ik B kj
k 1
T (n) O (n )
3
C 11 A 11 B 11 A 12 B 21
C 12 A 11 B 12 A 12 B 22
C 21 A 21 B 11 A 22 B 21
C 22 A 21 B 12 A 22 B 22
143
n
T (n) 8 T ( ) an
2
2
O (n )
3
144
Example: use Divide-and-Conquer way to solve it as following:
1 1 1 1 1 1 1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 1 1 1
1 1 1 0 1 1 1 0 3 3 3 0
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 0 1 1 3 3
C 11
1 1 1 1 1 0 0 0 3 3
1 1 1 0 1 0 1 0 3 0
C 12
1 1 1 0 1 0 0 0 3 0
1 1 1 1 1 0 1 1 3 3
C 21
0 0 1 1 0 0 0 0 0 0
1 1 1 0 1 0 1 0 3 0
C 22
0 0 1 0 0 0 0 0 0 0
145
Strassen’s Matrix Multiplication
Strassens introduces new way of computing the Cij’s using 7
multiplications and 18 additions or subtractions
P ( A 11 A 22 )( B 11 B 22 )
Q ( A 21 A 22 ) B 11
R A 11 ( B 12 B 22 )
S A 22 ( B 21 B 11 )
T ( A 11 A 12 ) B 22
U ( A 21 A 11 )( B 11 B 12 )
V ( A 12 A 22 )( B 21 B 22 )
C 11 P S T V
C 12 R T
C 21 Q S
C 22 P R Q U
146
Analysis
n
7 T ( ) an n 2
2
T (n) 2
b n 2
n 2
T (n) 7 T ( ) an
2
2 n 7 2 2
7 T ( ) ( ) an an
2
2 4
3 n 7 2 2 7 2 2
7 T ( ) ( ) an ( ) an an
3
2 4 4
147
Analysis
Assume n = 2k for some integer k
k 1 n 7 k2
7 T ( ) an ( ) 1
2
k 1
2 4
7 k 1
( ) 1
k 1 4
7 b an
2
7
1
4
7
b 7 cn (
k 2 k
)
4
7
7 Lg
b 7 cn ( b 7 cn
Lgn 2 Lgn Lgn 2 4
) (n )
4
bn cn (b c ) n
Lg 7 Lg 7 Lg 7
O (n ) O (n
Lg 7 2 . 81
)
148
GENERAL METHOD
• General Method
• Dynamic programming is a name, coined by Richard Bellman in
1955. Dynamic programming, as greedy method, is a powerful
algorithm design technique that can be used when the solution to
the problem may be viewed as the result of a sequence of
decisions.
• In the greedy method we make irrevocable decisions one at a time,
using a greedy criterion. However, in dynamic programming we
examine the decision sequence to see whether an optimal decision
sequence contains optimal decision subsequence.
• When optimal decision sequences contain optimal decision subsequences,
we can establish recurrence equations, called dynamic-programming
recurrence equations that enable us to solve the problem in an efficient
way.
• Dynamic programming is based on the principle of optimality (also coined
by Bellman). The principle of optimality states that no matter whatever
the initial state and initial decision are, the remaining decision sequence
must constitute an optimal decision sequence with regard to the state
resulting from the first decision.
• The principle implies that an optimal decision sequence is comprised of
optimal decision subsequences. Since the principle of optimality may not
hold for some formulations of some problems, it is necessary to verify that
it does hold for the problem being solved. Dynamic programming cannot
be applied when this principle does not hold.
• The steps in a dynamic programming solution are:
• Verify that the principle of optimality holds. Set up the dynamic-
programming recurrence equations. Solve the dynamic-
programming recurrence equations for the value of the optimal
solution. Perform a trace back step in which the solution itself is
constructed.
• Dynamic programming differs from the greedy method since the
greedy method produces only one feasible solution, which may or
may not be optimal, while dynamic programming produces all
possible sub-problems at most once, one of which guaranteed to be
optimal. Optimal solutions to sub-problems are retained in a table,
thereby avoiding the work of recomputing the answer every time a
sub-problem is encountered
• Two difficulties may arise in any application of dynamic
programming:
• 1. It may not always be possible to combine the solutions of smaller
problems to form the solution of a larger one.
• [Link] number of small problems to solve may be un-acceptably
large.
• There is no characterized precisely which problems can be
effectively solved with dynamic programming; there are many hard
problems for which it does not seen to be applicable, as well as
many easy problems for which it is less efficient than standard
algorithms.
MULTI STAGE GRAPHS
• A multistage graph G = (V, E) is a directed graph in which the
vertices are partitioned into k >2 disjoint sets Vi, 1 <i <k. In addition,
if <u, v> is an edge in E, then u Vi and v Vi+1 for some i, 1 <i <k.
• Let the vertex ‘s’ is the source, and ‘t’ the sink. Let c (i, j) be the cost
of edge <i, j>. The cost of a path from ‘s’ to ‘t’ is the sum of the
costs of the edges on the path.
• The multistage graph problem is to find a minimum cost path from
‘s’ to ‘t’. Each set Vi defines a stage in the graph. Because of the
constraints on E, every path from ‘s’ to ‘t’ starts in stage 1, goes to
stage 2, then to stage 3, then to stage 4, and so on, and eventually
terminates in stage k.
• A dynamic programming formulation for a k-stage graph problem is
obtained by first noticing that every stop path is the result of a
sequenceofk–[Link] ith
Decision involves determining which vertex in vi+1, 1 <i <k - 2, is to beon the
path. Let c (i, j) be the cost of the path from source to destination. Then using
the forward approach, we obtain:
Algorithm
• Algorithm Fgraph(G, k, n,p)
• // The input is a k-stage graph G = (V, E) with n vertices
• // indexed in order or stages. E is a set of edges and c [i,j]
• // is the cost of (i, j). p [1 : k] is a minimum cost path.
• {
• cost [n] :=0.0;
• for j:= n - 1 to 1 step – 1do
• { // compute cost[j]
• let r be a vertex such that (j, r) is an edge of G and c [j, r] + cost [r] is
minimum; cost [j] := c [j, r] + cost[r];
• d [j] :=r:
• }
• p [1] := 1; p [k] :=n; // Find a minimum cost path.
• for j := 2 to k - 1 do
• p [j] := d [p [j -1]];
• }
Algorithm
• Algorithm Bgraph(G, k, n,p)
• // Same function asFgraph
• {
• Bcost [1] :=0.0;
• for j := 2 to ndo
• { // Compute Bcost[j].
• Let r be such that (r, j) is an edge of G and Bcost [r] + c [r, j] is minimum;
Bcost [j] := Bcost [r] + c [r,j];
• D [j] :=r;
• } //find a minimum costpath
• p [1] := 1; p [k] :=n;
• for j:= k - 1 to 2 do p [j] := d [p [j +1]];
• }
OPTIMAL BINARY SEARCH
TREE(OBST)
• Let us assume that the given set of identifiers is {a1, . . . , an} with
a1 < a2 < . . . . < an. Let p (i) be the probability with which we search
for ai. Let q (i) be the probability that the identifier x being searched
for is such that ai < x < ai+1, 0 <i <n (assume a0 = - and an+1 =
+). We have to arrange the identifiers in a binary search tree in a
way that minimizes the expected total access time.
• In a binary search tree, the number of comparisons needed to
access an element at depth 'd' is d + 1, so if 'ai' is placed at depth
'di', then we want to minimize:
Example 1: The possible binary search trees for the identifier set (a1, a2, a3) =
(do, if, stop) are as follows. Given the equal probabilities p (i) = Q (i) = 1/7 for
all i, we have:
• Example1:
• Let n = 4, and (a1, a2, a3, a4) = (do, if, need, while) Let P (1: 4) = (3,
3, 1, 1) and Q (0: 4) = (2, 3, 1, 1,1)
• First, computing all C (i, j) such that j - i = 1; j = i + 1 and as 0 <i < 4; i
= 0, 1, 2 and 3; i < k ≤ J. Start with i = 0; so j = 1; as i < k ≤ j, so the
possible value for k =1
• W (0, 1) = P (1) + Q (1) + W (0, 0) = 3 + 3 + 2 =8
• C (0, 1) = W (0, 1) + min {C (0, 0) + C (1, 1)} =8
• R (0, 1) = 1 (value of 'K' that is minimum in the above equation).
Next with i = 1; so j = 2; as i < k ≤ j, so the possible value for k =2
• W (1, 2) = P (2) + Q (2) + W (1, 1) = 3 + 1 + 3 =7
• C (1, 2) = W (1, 2) + min {C (1, 1) + C (2, 2)} =7
• R (1, 2) =2
•
• Next with i = 2; so j = 3; as i < k ≤ j, so the possible value for k =3
• W (2, 3) = P (3) + Q (3) + W (2, 2) = 1 + 1 + 1 =3
• C (2, 3) = W (2, 3) + min {C (2, 2) + C (3, 3)} = 3 + [(0 + 0)] =3
• R (2, 3) =3
• Next with i = 3; so j = 4; as i < k ≤ j, so the possible value for k =4 W
(3, 4) = P (4) + Q (4) + W (3, 3) = 1 + 1 + 1 =3
• C (3, 4) = W (3, 4) + min {[C (3, 3) + C (4, 4)]} = 3 + [(0 + 0)] =3
• R (3, 4) =4
• Second, Computing all C (i, j) such that j - i = 2; j = i + 2 and as 0 <i <
3; i = 0, 1, 2; i < k ≤ J. Start with i = 0; so j = 2; as i < k ≤ J, so the
possible values for k = 1 and2.
•
• W (0, 2) = P (2) + Q (2) + W (0, 1) = 3 + 1 + 8 =12
• C (0, 2) = W (0, 2) + min {(C (0, 0) + C (1, 2)), (C (0, 1) + C (2,2))}
• = 12 + min {(0 + 7, 8 + 0)} =19
• R (0, 2) =1
• Next, with i = 1; so j = 3; as i < k ≤ j, so the possible value for k = 2
and3.
•
• W (1, 3) = P (3) + Q (3) + W (1, 2) = 1 + 1+ 7 =9
• C (1, 3) = W (1, 3) + min {[C (1, 1) + C (2, 3)], [C (1, 2) + C (3,3)]}
• = W (1, 3) + min {(0 + 3), (7 + 0)} = 9 + 3 =12
• R (1, 3) =2
• Next, with i = 2; so j = 4; as i < k ≤ j, so the possible value for k = 3
and 4. W (2, 4) = P (4) + Q (4) + W (2, 3) = 1 + 1 + 3 =5
• C (2, 4) = W (2, 4) + min {[C (2, 2) + C (3, 4)], [C (2, 3) + C (4,4)]
• = 5 + min {(0 + 3), (3 + 0)} = 5 + 3 =8
• R (2, 4) =3
• Third, Computing all C (i, j) such that J - i = 3; j = i + 3 and as 0 <i < 2; i =
0,1;
• i < k ≤ J. Start with i = 0; so j = 3; as i < k ≤ j, so the possible values for k = 1,
2 and3.
• W (0, 3) = P (3) + Q (3) + W (0, 2) = 1 + 1 + 12 =14
• C (0, 3) = W (0, 3) + min {[C (0, 0) + C (1, 3)], [C (0, 1) + C (2,3)],
• [C (0, 2) + C (3,3)]}
• = 14 + min {(0 + 12), (8 + 3), (19 + 0)} = 14 + 11 =25
• R (0, 3) =2
• Start with i = 1; so j = 4; as i < k ≤ j, so the possible values for k = 2, 3 and4.
W (1, 4) = P (4) + Q (4) + W (1, 3) = 1 + 1 + 9 =11
• C (1, 4) = W (1, 4) + min {[C (1, 1) + C (2, 4)], [C (1, 2) + C (3,4)],
• [C (1, 3) + C (4,4)]}
• = 11 + min {(0 + 8), (7 + 3), (12 + 0)} = 11 + 8 =19
• R (1, 4) =2
• Fourth, Computing all C (i, j) such that j - i = 4; j = i + 4 and as 0 <i <
1; i = 0; i < k ≤J.
• Start with i = 0; so j = 4; as i < k ≤ j, so the possible values for k = 1,
2, 3 and4.
• W (0, 4) = P (4) + Q (4) + W (0, 3) = 1 + 1 + 14 =16
• C (0, 4) = W (0, 4) + min {[C (0, 0) + C (1, 4)], [C (0, 1) + C (2,4)],
• [C (0, 2) + C (3, 4)], [C (0, 3) + C (4,4)]}
• = 16 + min [0 + 19, 8 + 8, 19+3, 25+0] = 16 + 16 =32
• R (0, 4) =2
• From the table we see that C (0, 4) = 32 is the minimum cost of a
binary search tree for (a1, a2, a3, a4). The root of the tree 'T04'
is'a2'.
• Hence the left sub tree is 'T01' and right sub tree is T24. The root of
'T01' is 'a1' and the root of 'T24' isa3.
• The left and right sub trees for 'T01' are 'T00' and 'T11'
respectively. The root of T01 is 'a1'
•
• The left and right sub trees for T24 are T22 and T34 respectively.
The root of T24 is'a3'.
• The root of T22 is null The root of T34 is a4.
0/1 –KNAPSACK
• We are given n objects and a knapsack. Each object i has a positive weight
wi and a positive value Vi. The knapsack can carry a weight not exceeding
W. Fill the knapsack so that the value of objects in the knapsack is
optimized.
• A solution to the knapsack problem can be obtained by making a
sequence of decisions on the variables x1, x2, . . . . , xn. A decision on
variable xi involves determining which of the values 0or1 is to be assigned
to [Link] us assume that decisions on the xi are made in the order xn, xn-1,
. . . .x1. Following a decision on xn, we may be in one of two possible
states: the capacity remaining in m – wn and a profit of pn has accrued.
It is clear that the remaining decisions xn-1, . . . , x1 must be
optimal with respect to the problem state resulting from the
decision on xn. Otherwise, xn,. . . . , x1 will not be optimal. Hence,
the principal of optimality holds.
• Solution:
• Initially, fo (x) = 0, for all x and fi (x) = - if x < 0. Fn (M) = max {fn-1
(M), fn-1 (M - wn) +pn}
• F3 (6) = max (f2 (6), f2 (6 – 4) + 5} = max {f2 (6), f2 (2) +5}
• F2 (6) = max (f1 (6), f1 (6 – 3) + 2} = max {f1 (6), f1 (3) +2}
• F1 (6) = max (f0 (6), f0 (6 – 2) + 1} = max {0, 0 + 1} =1
• F1 (3) = max (f0 (3), f0 (3 – 2) + 1} = max {0, 0 + 1} =1
• Therefore, F2 (6) = max (1, 1 + 2} =3
• F2 (2) = max (f1 (2), f1 (2 – 3) + 2} = max {f1 (2), - 0+ 2}
• F1 (2) = max (f0 (2), f0 (2 – 2) + 1} = max {0, 0 + 1} =1
• F2 (2) = max {1, - 0+ 2} =1
• Finally, f3 (6) = max {3, 1 + 5} =6
All pairs shortest path
Problem
• In the all pairs shortest path problem, we are to find a shortest path
between every pair of vertices in a directed graph G. That is, for every pair
of vertices (i, j), we are to find a shortest path from i to j as well as one
from j to i. These two paths are the same when G is undirected.
• When no edge has a negative length, the all-pairs shortest path problem
may be solved by using Dijkstra’s greedy single source algorithm n times,
once with each of the n vertices as the source vertex.
• The all pairs shortest path problem is to determine a matrix A such that A
(i, j) is the length of a shortest path from i to j. The matrix A can be
obtained by solving n single-source problems using the algorithm shortest
Paths. Since each application of this procedure requires O (n2) time, the
matrix A can be obtained in O (n3) time.
• In the all pairs shortest path problem, we are to find a shortest path
between every pair of vertices in a directed graph G. That is, for every
pair of vertices (i, j), we are to find a shortest path from i to j as well as
one from j to i. These two paths are the same when G is undirected.
• When no edge has a negative length, the all-pairs shortest path
problem may be solved by using Dijkstra’s greedy single source
algorithm n times, once with each of the n vertices as the source
vertex.
• The all pairs shortest path problem is to determine a matrix A such that
A (i, j) is the length of a shortest path from i to j. The matrix A can be
obtained by solving n single-source problems using the algorithm
shortest Paths. Since each application of this procedure requires O (n2)
time, the matrix A can be obtained in O (n3)time.
• The shortest i to j path in G, i ≠ j originates at vertex i and goes
through some intermediate vertices (possibly none) and terminates
at vertex j. If k is an intermediate vertex on this shortest path, then
the subpaths from i to k and from k to j must be shortest paths
from i to k and k to j, respectively.
• Otherwise, the i to j path is not of minimum length. So, the
principle of optimality holds. Let Ak (i, j) represent the length of a
shortest path from i to j going through no vertex of index greater
than k, we obtain:
• Ak (i, j) = {min {min {Ak-1 (i, k) + Ak-1 (k, j)}, c (i,j)}
• 1<k<n
• Algorithm All Paths (Cost, A,n)
• // cost [1:n, 1:n] is the cost adjacency matrix of a graph which
• // n vertices; A [I, j] is the cost of a shortest path from vertex
• // i to vertex j. cost [i, i] = 0.0, for 1 <i <n.
• {
• for i := 1 to n do
• for j:= 1 to n do
• A [i, j] := cost [i,j]; // copy cost into A
• for k := 1 to n do
• for i := 1 to n do
• for j := 1 to n do
• A [i, j] := min (A [i, j], A [i, k] + A [k,j]);
• }
• General formula: min {Ak-1 (i, k) + Ak-1 (k, j)}, c (i,j)}
• 1<k<n
• Solve the problem for different values of k = 1, 2 and3
• Step 1: Solving the equation for, k =1;
• A1 (1, 1) = min {(Ao (1, 1) + Ao (1, 1)), c (1, 1)} = min {0 + 0, 0} =0
• A1 (1, 2) = min {(Ao (1, 1) + Ao (1, 2)), c (1, 2)} = min {(0 + 4), 4} =4
• A1 (1, 3) = min {(Ao (1, 1) + Ao (1, 3)), c (1, 3)} = min {(0 + 11), 11} =11
• A1 (2, 1) = min {(Ao (2, 1) + Ao (1, 1)), c (2, 1)} = min {(6 + 0), 6} =6
• A1 (2, 2) = min {(Ao (2, 1) + Ao (1, 2)), c (2, 2)} = min {(6 + 4), 0)} =0
• A1 (2, 3) = min {(Ao (2, 1) + Ao (1, 3)), c (2, 3)} = min {(6 + 11), 2} =2
• A1 (3, 1) = min {(Ao (3, 1) + Ao (1, 1)), c (3, 1)} = min {(3 + 0), 3} =3
• A1 (3, 2) = min {(Ao (3, 1) + Ao (1, 2)), c (3, 2)} = min {(3 + 4), 0} =7
• A1 (3, 3) = min {(Ao (3, 1) + Ao (1, 3)), c (3, 3)} = min {(3 + 11), 0} =0
• Step 2: Solving the equation for, K =2;
• A2 (1, 1) = min {(A1 (1, 2) + A1 (2, 1), c (1, 1)} = min {(4 + 6), 0} = 0
• A2 (1, 2) = min {(A1 (1, 2) + A1 (2, 2), c (1, 2)} = min {(4 + 0), 4} = 4
• A2 (1, 3) = min {(A1 (1, 2) + A1 (2, 3), c (1, 3)} = min {(4 + 2), 11} =6
• A2 (2, 1) = min {(A (2, 2) + A (2, 1), c (2, 1)} = min {(0 + 6), 6} =6
• A2 (2, 2) = min {(A (2, 2) + A (2, 2), c (2, 2)} = min {(0 + 0), 0} =0
• A2 (2, 3) = min {(A (2, 2) + A (2, 3), c (2, 3)} = min {(0 + 2), 2} =2
• A2 (3, 1) = min {(A (3, 2) + A (2, 1), c (3, 1)} = min {(7 + 6), 3} =3
• A2 (3, 2) = min {(A (3, 2) + A (2, 2), c (3, 2)} = min {(7 + 0), 7} =7
• A2 (3, 3) = min {(A (3, 2) + A (2, 3), c (3, 3)} = min {(7 + 2), 0} =0
• Step 3: Solving the equation for, k =3;
• A3 (1, 1) = min {A2 (1, 3) + A2 (3, 1), c (1, 1)} = min {(6 + 3), 0} =0
• A3 (1, 2) = min {A2 (1, 3) + A2 (3, 2), c (1, 2)} = min {(6 + 7), 4} =4
• A3 (1, 3) = min {A2 (1, 3) + A2 (3, 3), c (1, 3)} = min {(6 + 0), 6} =6
• A3 (2, 1) = min {A2 (2, 3) + A2 (3, 1), c (2, 1)} = min {(2 + 3), 6} =5
• A3 (2, 2) = min {A2 (2, 3) + A2 (3, 2), c (2, 2)} = min {(2 + 7), 0} =0
• A3 (2, 3) = min {A2 (2, 3) + A2 (3, 3), c (2, 3)} = min {(2 + 0), 2} =2
• A3 (3, 1) = min {A2 (3, 3) + A2 (3, 1), c (3, 1)} = min {(0 + 3), 3} =3
• A3 (3, 2) = min {A2 (3, 3) + A2 (3, 2), c (3, 2)} = min {(0 + 7), 7} =7
• A3 (3, 3) = min {A2 (3, 3) + A2 (3, 3), c (3, 3)} = min {(0 + 0), 0} =0
TRAVELLING SALES PERSON
PROBLEM
• Let G = (V, E) be a directed graph with edge costs Cij. The variable cijis
defined such that cij> 0 for all I and j and cij= if < i, j>E.
• Let |V| = n and assume n > 1. A tour of G is a directed simple cycle that
includes every vertex in V. The cost of a tour is the sum of the cost of the
edges on the tour.
• The traveling sales person problem is to find a tour of minimum cost. The
tour is to be a simple path that starts and ends at vertex1.
• Let g (i, S) be the length of shortest path starting at vertex i, going through
all vertices in S, and terminating at vertex 1. The function g (1, V – {1}) is
the length of an optimal salesperson tour. From the principal of optimality
it followsthat:
• C(S, i) = min { C(S-{i}, j) + dis(j, i)} where j belongs to S, j != i and j != 1.
• Example1:
• For the following graph find minimum cost tour for the traveling
sales person problem:
• Clearly, g (i, 0) = ci1 , 1 ≤ i ≤ n.
• g (2, 0) = C21 =5
• g (3, 0) = C31 = 6 g (4, 0) = C41 =8
• Using equation – (2) we obtain:
• g (1, {2, 3, 4}) = min {c12 + g (2, {3, 4}, c13 + g (3, {2, 4}), c14 + g (4, {2,3})}
• g (2, {3, 4}) = min {c23 + g (3, {4}), c24 + g (4,{3})}
• = min {9 + g (3, {4}), 10 + g (4,{3})}
• g (3, {4}) = min {c34 + g (4, 0)} = 12 + 8 =20
• g (4, {3}) = min {c43 + g (3, 0)} = 9 + 6 =15
•
•
• Therefore, g (2, {3, 4}) = min {9 + 20, 10 + 15} = min {29, 25} =25
• g (3, {2, 4}) = min {(c32 + g (2, {4}), (c34 + g (4,{2})}
• g (2, {4}) = min {c24 + g (4, 0)} = 10 + 8 =18
• g (4, {2}) = min {c42 + g (2, 0)} = 8 + 5 =13
• Therefore, g (3, {2, 4}) = min {13 + 18, 12 + 13} = min {41, 25} =25
• g (4, {2, 3}) = min {c42 + g (2, {3}), c43 + g (3,{2})}
• g (2, {3}) = min {c23 + g (3, 0} = 9 + 6 =15
• g (3, {2}) = min {c32 + g (2, 0} = 13 + 5 =18
• Therefore, g (4, {2, 3}) = min {8 + 15, 9 + 18} = min {23, 27} =23
• g (1, {2, 3, 4}) = min {c12 + g (2, {3, 4}), c13 + g (3, {2, 4}), c14 + g (4,
{2,3})}= min {10 + 25, 15 + 25, 20 + 23} = min {35, 40, 43} =35
• The optimal tour for the graph has length = 35 The optimal tour is:
1, 2, 4, 3,1.
BACKTRACKING: GENERAL
METHOD
BACKTRACKING: GENERAL METHOD:
• Solution states are the problem states „S‟ for which the
path from the root node to „S‟ defines a tuple in the
solution space.
• Answer states are those solution states for which the path
from root node to s defines a tuple that is a member of the
set of solutions.
• State space is the set of paths from root node to other
nodes. State space tree is the tree organization of the
solution space. The state space trees are called static trees.
This terminology follows from the observation that the tree
organizations are independent of the problem instance
being solved. For some problems it is advantageous to use
different tree organizations for different problem instance.
• Branch and Bound refers to all state space search methods in which
all children of an E-node are generated before any other live node
can become the E-node.
• Diag 45 conflict: Two queens i and j are on the same 450 diagonal if:
• i – j = k – l.
• This implies, j – l = i – k
Step 2:
• If this new sequence is feasible and has length 8 then STOP with a
solution. If the new sequence is feasible and has length less then 8,
repeat Step 1.
Step 3:
• If the sequence is not feasible, then backtrack through the
sequence until we find the most recent place at which we can
exchange a value. Go back to Step 1.
4-queens problem
4-queens problem
• Let us see how backtracking works on the 4-queens
problem. We start with the root node as the only live
node. This becomes the E-node. We generate one
child.
• Let us assume that the children are generated in
ascending order. Thus node number 2 of figure is
generated and the path is now (1). This corresponds to
placing queen 1 on column 1. Node 2 becomes the E-
node. Node 3 is generated and immediately killed.
• The next node generated is node 8 and the path
becomes (1, 3). Node 8 becomes the E-node. However,
it gets killed as all its children represent board
configurations that cannot lead to an answer node. We
backtrack to node 2 and generate another child, node
13.
• The path is now (1, 4). The board configurations as
backtracking proceeds are as follows:
• The above figure shows graphically the steps that the
backtracking algorithm goes through as it tries to find a
solution. The dots indicate placements of a queen, which
were tried and rejected because another queen was
attacking.
• In Figure (b) the second queen is placed on columns 1 and 2
and finally settles on column 3. In figure (c) the algorithm
tries all four columns and is unable to place the next queen
on a square. Backtracking now takes place. In figure (d) the
second queen is moved to the next possible column,
column 4 and the third queen is placed on column 2. The
boards in Figure (e), (f), (g), and (h) show the remaining
steps that the algorithm goes through until a solution is
found.
Sum of Subsets
Sum of Subsets
• Given positive numbers wi, 1 ≤ i ≤ n, and m, this problem
requires finding all subsets of wi whose sums are „m‟.
• All solutions are k-tuples, 1 ≤ k ≤ n. Explicit constraints:
• xi Є {j | j is an integer and 1 ≤ j ≤ n}.
• Implicit constraints:
• No two xi can be the same.
Naive Algorithm
Generate all possible configurations of queens on board and print a configuration
that satisfies the given constraints.
• while there are untried conflagrations{ generate the next configuration if queens
don't attack in this configuration then
• { print this configuration;
• }
• }
Backtracking Algorithm
•
The idea is to place queens one by one in different columns, starting from
the leftmost column. When we place a queen in a column, we check for
clashes with already placed queens. In the current column, if we find a row
for which there is no clash, we mark this row and column as part of the
solution. If we do not find such a row due to clashes then we backtrack and
return false.
• 1) Start in the leftmost column
• 2) If all queens are placed return true
• 3) Try all rows in the current column. Do following for every tried row.
• a) If the queen can be placed safely in this row then mark this [row,
column] as part of the solution and recursively check if placing queen
here leads to a solution.
• b) If placing queen in [row, column] leads to a solution then return true.
• c) If placing queen doesn't lead to a solution then umark this [row,
column] (Backtrack) and go to step (a) to try other rows.
• 3) If all rows have been tried and nothing worked, return false to trigger
backtracking.
Implementation of Backtracking
solution
• # Python program to solve N Queen using backtracking
• global N
• N=4
• def printSolution(board):
• for i in range(N):
• for j in range(N):
• print board[i][j],
• print
•
• # A utility function to check if a queen can # be placed on board[row][col].
Note that this # function is called when "col" queens are # already placed
in columns from 0 to col -1.
• # So we need to check only left side for # attacking queens
• def isSafe(board, row, col): # Check this row on left side
• for i in range(col):
• if board[row][i] == 1:
• return False # Check upper diagonal on left side
• for i,j in zip(range(row,-1,-1), range(col,-1,-1)):
• if board[i][j] == 1:
• # Check lower diagonal on left side
• for i,j in zip(range(row,N,1), range(col,-1,-1)):
• if board[i][j] == 1:
• return False
• return True
•
• def solveNQUtil(board, col):
• # base case: If all queens are placed # then return true
• if col >= N:
• return True
•
• # Consider this column and try placing # this queen in all rows one by one
• for i in range(N):
• if isSafe(board, i, col):
• # Place this queen in board[i][col]
• board[i][col] = 1
• # recur to place rest of the queens
• if solveNQUtil(board, col+1) == True:
• return True
• # If placing queen in board[i][col # doesn't lead to a solution, then # queen
from board[i][col]
• board[i][col] = 0
•
• # if queen can not be place in any row in # this colum col then return false
• return False
• # This function solves the N Queen problem using # Backtracking. It mainly uses
solveNQUtil() to
• # solve the problem. It returns false if queens # cannot be placed, otherwise return
true and
• # placement of queens in the form of 1s. # note that there may be more than one
• # solutions, this function prints one of the # feasible solutions.
• def solveNQ():
• board = [ [0, 0, 0, 0],
• [0, 0, 0, 0],
• [0, 0, 0, 0],
• [0, 0, 0, 0]
• ]
• if solveNQUtil(board, 0) == False:
• print "Solution does not exist"
• return False
• printSolution(board)
• return True
• # driver program to test above function
Applications-8-Queens Problem
• Let us consider, N = 8. Then 8-Queens Problem is to place
eight queens on an 8 x 8 chessboard so that no two
“attack”, that is, no two of them are on the same row,
column, or diagonal.
• All solutions to the 8-queens problem can be represented
as 8-tuples (x1, . . . . , x8), where xi is the column of the ith
row where the ith queen is placed.
• The explicit constraints using this formulation are Si = {1, 2,
3, 4, 5, 6, 7, 8}, 1 < i < 8. Therefore the solution space
consists of 88 8-tuples.
• Diag 45 conflict: Two queens i and j are on the same 450 diagonal if:
• i – j = k – l.
• This implies, j – l = i – k
• In both LIFO and FIFO Branch and Bound the selection rule for the next E-
node in rigid and blind. The selection rule for the next E-node does not
give any preference to a node that has a very good chance of getting the
search to an answer node quickly.
• The search for an answer node can be speeded by using an “intelligent”
ranking Function c( .) for live nodes. The next E-node is selected on the
basis of this ranking function. The node x is assigned a rank using:
• c ( x ) = f(h(x)) + g ( x )
• h(x) is the cost of reaching x from the root and f(.) is any non-decreasing
function.
• g ( x ) is an estimate of the additional effort needed to reach an answer
node from x.
• We associate a cost c(x) with each node x in the state space tree. It is not
possible to easily compute the function c(x). So we compute a estimate c (
x ) of c(x).
Control Abstraction for LC-Search:
• Let t be a state space tree and c() a cost function for the nodes in t.
If x is a node in t, then c(x) is the minimum cost of any answer node
in the subtree with root x. Thus, c(t) is the cost of a minimum-cost
answer node in t.
• A heuristic c (.) is used to estimate c(). This heuristic should be easy
to compute and
• generally has the property that if x is either an answer node or a
leaf node, then c(x) =c( x ).
• Least() finds a live node with least c(). This node is deleted from the
list of live nodes and returned.
• Add(x) adds the new live node x to the list of live
nodes. The list of live nodes be implemented as a min-
heap.
• Algorithm LCSearch outputs the path from the answer
node it finds to the root node t. This is easy to do if
with each node x that becomes live, we associate a
field parent which gives the parent of node x. When
the answer node g is found, the path from g to t can be
determined by following a sequence of parent values
starting from the current E-node (which is the parent
of g) and ending at node t.
• Listnode = record
• {
• Listnode * next, *parent; float cost;
• }
• Algorithm LCSearch(t)
• { //Search t for an answer node
• if *t is an answer node then output *t and return; E := t; //E-node.
• initialize the list of live nodes to be empty; repeat
• {
• for each child x of E do
• {
• if x is an answer node then output the path from x to t and return; Add (x);
//x is a new live node.
• (x à parent) := E; // pointer for path to root
• }
• if there are no more live nodes then
• {
• write (“No answer node”); return;
• }
• E := Least();
• } until (false);
• }
• The root node is the first, E-node. During the execution of
LC search, this list contains all live nodes except the E-node.
Initially this list should be empty. Examine all the children
of the E-node, if one of the children is an answer node,
then the algorithm outputs the path from x to t and
terminates. If the child of E is not an answer node, then it
becomes a live node. It is added to the list of live nodes and
its parent field set to E.
• When all the children of E have been generated, E becomes
a dead node. This happens only if none of E‟s children is an
answer node. Continue the search further until no live
nodes found. Otherwise, Least(), by definition, correctly
chooses the next E-node and the search continues from
here.
• LC search terminates only when either an
answer node is found or the entire state space
tree has been generated and searched.
Bounding
Bounding
• A branch and bound method searches a state space tree using any search
mechanism in which all the children of the E-node are generated before
another node becomes the E-node. We assume that each answer node x
has a cost c(x) associated with it and that a minimum-cost answer node is
to be found. Three common search strategies are FIFO, LIFO, and LC. The
three search methods differ only in the selection rule used to obtain the
next E-node.
•
• A good bounding helps to prune efficiently the tree, leading to a faster
exploration of the solution space.
•
• A cost function c(.) such that c ( x ) < c(x) is used to provide lower
bounds on solutions obtainable from any node x. If upper is an upper
bound on the cost of a minimum-cost solution, then all live nodes x with
c(x) >c ( x ) > upper. The starting value for upper can be obtained by some
heuristic or can be set to ∞
• As long as the initial value for upper is not less than the cost of a
minimum-cost answer node, the above rules to kill live nodes will
not result in the killing of a live node that can reach a minimum-
cost answer node. Each time a new answer node is found, the value
of upper can be updated.
•
• Branch-and-bound algorithms are used for optimization problems
where, we deal directly only with minimization problems. A
maximization problem is easily converted to a minimization
problem by changing the sign of the objective function.
•
• To formulate the search for an optimal solution for a least-cost
answer node in a state space tree, it is necessary to define the cost
function c(.), such that c(x) is minimum for all nodes representing
an optimal solution. The easiest way to do this is to use the
objective function itself for c(.).
• For nodes representing feasible solutions, c(x) is the value of the
objective function for that feasible solution.
• The 15 puzzle is to search the state space for the goal state and use the
path from the initial state to the goal state as the answer. There are 16!
(16! ≈ 20.9 x 1012) different arrangements of the tiles on the frame.
• As the state space for the problem is very large it would be worthwhile to
determine whether the goal state is reachable from the initial state.
Number the frame positions 1 to 16.
•
• Position i is the frame position containing title numbered i in the goal
arrangement of Figure 8.1(b). Position 16 is the empty spot. Let position(i)
be the position number in the initial state of the title number i. Then
position(16) will denote the position of the empty spot.
• For any state let: less(i) be the number of tiles j such that j < i and
position(j) > position(i).
• The goal state is reachable from the initial state iff
• LC Search for 15 Puzzle Problem:
• A depth first state space tree generation will result in the subtree of Figure
8.3 when the next moves are attempted in the order: move the empty
space up, right, down and left. The search of the state space tree is blind.
It will take the leftmost path from the root regardless of the starting
configuration. As a result, the answer node may never be found.
• A breadth first search will always find a goal node nearest to the root.
However, such a search is also blind in the sense that no matter what the
initial configuration, the algorithm attempts to make the same sequence
of moves.
• Node 2 becomes the next E-node. Its children, nodes 6, 7 and 8 are
generated.
• Then u(6) = 9 and so upper is updated to 9. The cost gets killed. Node 8 is
infeasible and so it is killed.
• c(7) = 10 > upper and node 7
• Next, node 3 becomes the E-node. Nodes 9 and
10 are now generated. Then u(9) =8 and so upper
becomes 8.
• The cost c(10) = 11 > upper, and this node is
killed.
• The next E-node is node 6. Both its children are
infeasible. Node 9‟s only child is also infeasible.
The minimum-cost answer node is node 9. It has
a cost of 8.
•
• When implementing a FIFO branch-and-bound
algorithm, it is not economical to kill live nodes
with c(x) > upper each time upper is updated.
This is so because live nodes are in the queue in
the order in which they were generated.
• Hence, nodes with c(x) with > upper are
distributed in some random way in the queue.
Instead, live nodes c(x) > upper can be killed
when they are about to become E-nodes.
LC Branch and Bound
• An LC Branch-and-Bound search of the tree of Figure 8.4
will begin with upper = ∞ and node 1 as the first E-node.
Optimization Problem
Optimization problems are those for which the objective is to maximize or
minimize some values. For example,
Finding the minimum number of colors needed to color a given
[Link] the shortest path between two vertices in a graph.
Decision Problem
There are many problems for which the answer is a Yes or a No. These
types of problems are known as decision problems. For example,Whether
a given graph can be colored by only 4-colors.
Finding Hamiltonian cycle in a graph is not a decision problem, whereas
checking a graph is Hamiltonian or not is a decision problem.
Basic concepts
P-Class
The class P consists of those problems that are solvable in
polynomial time, i.e. these problems can be solved in time O(nk) in
worst-case, where k is constant.
These problems are called tractable, while others are
called intractable or superpolynomial.
Formally, an algorithm is polynomial time algorithm, if there exists a
polynomial p(n) such that the algorithm can solve any instance of
size n in a time O(p(n)).
Basic concepts
NP-Class
The class NP consists of those problems that are verifiable in polynomial
time. NP is the class of decision problems for which it is easy to check the
correctness of a claimed answer, with the aid of a little extra information.
Hence, we aren’t asking for a way to find a solution, but only to verify that
an alleged solution really is correct.
Every problem in this class can be solved in exponential time using
exhaustive search.
P versus NP
Every decision problem that is solvable by a deterministic polynomial time
algorithm is also solvable by a polynomial time non-deterministic
algorithm.
All problems in P can be solved with polynomial time algorithms, whereas
all problems in NP - P are intractable.
•
Non-deterministic algorithms
Non-deterministic algorithms
As we have seen, a state space is a useful abstraction in analyzing
problems. The value of the abstraction is that it provides a particular
kind of modularization: One can consider separately the space to be
searched and the algorithm used to search it.
The class of NP-hard problems is very rich in the sense that it contains
many problems from a wide variety of disciplines.
The classes NP - Hard and
NP complete
P: The class of problems which can be solved by a deterministic
polynomial algorithm.
NP: The class of decision problem which can be solved by a non-
deterministic polynomial algorithm.
Phase 2: Checking
The classes NP - Hard and
NP complete
If the checking stage of a non deterministic algorithm is of polynomial
time- complexity, then this algorithm is called an NP (nondeterministic
polynomial) algorithm.
NP problems : (must be decision problems)
–e.g. searching, MST Sorting
Satisfy ability problem (SAT) travelling salesperson problem (TSP)
Example of a non deterministic algorithm
// The problem is to search for an element x //
// Output j such that A(j) =x; or j=0 if x is not in A // j choice (1 :n )
if A(j) =x then print(j) ; success endif print (‘0’) ; failure
complexity 0(1);
Non-deterministic decision algorithms generate a zero or one as their
output.
Deterministic search algorithm complexity is n.
The classes NP - Hard and
NP complete
The classes NP - Hard and NP
complete
Satisfiability:
Letx1, x2, x3…. xn denotes Boolean variables.
Let xi denotes the relation of xi.
A literal is either a variable or its negation.
A formula in the prepositional calculus is an expression that can be constructed
using literals and the operators and ^ or v.
A clause is a formula with at least one positive literal.
The satisfy ability problem is to determine if a formula is true for some
assignment of truth values to the variables.
It is easy to obtain a polynomial time non determination algorithm that
terminates s successfully if and only if a given prepositional formula E(x1,
x2……xn) is satiable.
Such an algorithm could proceed by simply choosing (non deterministically)
one of the 2n possible assignment so f truth values to (x1, x2…xn) and verify
that E(x1,x2…xn) is true for that assignment.
The classes NP - Hard and
NP complete
•The satisfy ability problem:
The logical formula:
x1v x2 v x3 & -x1 & -x2
the assignment : x1 ← F , x2 ← F , x3 ← T will make the above
formula true . (-x1, -x2, x3) represents x1 ← F, x2 ← F, x3 ← T
If there is at least one assignment which satisfies a formula, then we
say that this formula is satisfiable; otherwise, it is un satisfiable.
An un satisfiable formula:
Generating optimal code for level one directed a-cyclic graphs is NP-hard
but optimal code for trees can be generated in polynomial time.
Cliques:
Theorem-1
If a set S of strings is accepted by some non-deterministic Turing
machine within polynomial time, then S is P-reducible to {DNF
tautologies}.
Cook's theorem
Theorem-2
The following sets are P-reducible to each other in pairs (and hence
each has the same polynomial degree of difficulty): {tautologies}, {DNF
tautologies}, D3, {sub-graph pairs}.
Theorem-3
For any TQ(k) of type Q, TQ(k)k√(logk)2TQ(k)k(logk)2 is unbounded
There is a TQ(k) of type Q such that TQ(k)⩽2k(logk)2TQ(k)⩽2k(logk)2
Cook's theorem
Theorem-4
If the set S of strings is accepted by a non-deterministic machine within
time T(n) = 2n, and if TQ(k) is an honest (i.e. real-time countable)
function of type Q, then there is a constant K, so S can be recognized by
a deterministic machine within time TQ(K8n).
Cook's theorem
Cook's theorem
Cook’s Theorem
Cook’s Theorem states that Any NP problem can be converted to
SAT in polynomial time.
In order to prove this, we require a uniform way of representing NP
problems. Remember that what makes a problem NP is the existence of
a polynomial-time algorithm—more specifically, a Turing machine—for
checking candidate certificates. What Cook did was somewhat
analogous to what Turing did when he showed that the Entscheidungs
problem was equivalent to the Halting Problem. He showed how to
encode as Propositional Calculus clauses both the relevant facts about
the problem instance and the Turing machine which does the
certificate-checking, in such a way that the resulting set of clauses is
satisfiable if and only if the original problem instance is positive. Thus
the problem of determining the latter is reduced to the problem of
determining the former.
Cook's theorem
Let us assume that M has q states numbered 0, 1, 2, . . . , q 1, and a tape
alphabet a1, a2, . . . , as. We shall assume that the operation of the
machine is governed by the functions T , U , and D as described in the
chapter on the Entscheidungsproblem. We shall further assume that the
initial tape is inscribed with the problem instance on the squares 1, 2, 3,
. . . , n, and the putative certificate on the squares m, . . . , 2, 1. Square
zero can be assumed to contain a designated separator symbol. We shall
also assume that the machine halts scanning square 0, and that the
symbol in this square at that stage will be a1 if and only if the candidate
certificate is a true certificate. Note that we must have m P (n). This is
because with a problem instance of length n the computation is
completed in at most P (n) steps; during this process, the Turing
machine head cannot move more than P (n) steps to the left of its
starting point.
Cook's theorem
We define some atomic propositions with their intended
interpretations as follows:
−
For i = 0, 1, . . . , P (n) and j = 0, 1, . . . , q 1, the proposition Qij says that
after i computation steps, M is in state j.