Daa Pce
Daa Pce
Introduction to
Design and Analysis of Algorithm
An algorithm, named after the ninth century scholar Abu Jafar Muhammad Ibn Musa Al-
Khowarizmi, is defined as follows: Roughly speaking:
An algorithm is a set of rules for carrying out calculation either by hand or on a machine.
An algorithm is a finite step-by-step procedure to achieve a required result.
An algorithm is a sequence of computational steps that transform the input into the output.
An algorithm is a sequence of operations performed on data that have to be organized in data
structures.
An algorithm is an abstraction of a program to be executed on a physical machine (model of
Computation).
The most famous algorithm in history dates well before the time of the ancient Greek s: this is the
Euclid's algorithm for calculating the greatest common divisor of two integers. This theorem
appeared as the solution to the Proposition II in the Book VII of Euclid's "Elements." Euclid's
"Elements" consists of thirteen books, which contain a total number of 465 propositions.
We start with defining the model of computation(TOC). Once the model of computation has been
defined, an algorithm can be describe using a simple language (or pseudo language) whose syntax is
close to programming language such as C or java.
Algorithmic is a branch of computer science that consists of designing and analyzing computer
algorithms
Page 1
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
In this course students are learn various procedures and strategies to design algorithm and analysis of
design algorithms.
It helps to developed software in well manner. In software companies developers mainly performed
following tasks-
1. Design algorithm
2. Implementation
3. Testing
4. Analysis of algorithm
1. Design Algorithm:
2. Implementation:
3. Testing:
There are two phases-
Debugging:
Profiling:
Executing correct program on data sets and measuring time and space it takes to compute the results.
4. Analysis of algorithm:
Page 2
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Course Objectives:
To provide a solid foundation in algorithm design and analysis. Specifically, the student learning
outcomes include, Upon completion of this course, students will be able to do the following:
Page 3
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. Searching
2. Sorting
3. Hashing
4. Asymptotic Worst Case Time and Space Complexity.
5. Algorithm Design Techniques:
Divide and Conquer (DAC)
Greedy Method
Dynamic Programming
6. Graph Search
7. Minimum Spanning Trees
8. Shortest Paths.
Page 4
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT-I
Recurrence Relation
TOPICS:
1. Mathematical foundation
2. Summation of arithmetic and geometric series, Σn, Σn2
3. Bounding summation using integrations
4. Recurrence relations
5. Solutions of recurrence relations using technique of characteristic equation
6. Recursion tree method and master theorem
7. Complexity calculation of various standard functions
8. Principles of designing algorithms.
Page 5
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. Mathematical foundations:
The analysis of algorithms often requires us to draw upon a body of mathematical tools. Some of
these tools are as simple as high-school algebra, but others, such as solving recurrences, may be new
to you referred as mathematical foundation.
Summation:
When an algorithm contains an iterative control construct such as a while or for loop, its running
time can be expressed as the sum of the times spent on each execution of the body of the loop. By
adding up the time spent on each iteration, we obtained the summation or series
Evaluating this summation yielded a bound of (n2) on the worst-case running time of the
algorithm. This example indicates the general importance of understanding how to manipulate and
bound summations.
2. Given a sequence a1, a2, . . . Of numbers, the infinite sum a1 + a2 + can be written
Arithmetic series:
The summation
Which came up when we analyzed insertion sort, is an arithmetic series and has the value
Page 6
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Geometric series:
When the summation is infinite and |x| < 1, we have the infinite decreasing geometric series
The summation is represented as the area of the rectangles in the figure, and the integral is the
shaded region under the curve. When â(k) is a monotonically decreasing function, we can use a
similar method to provide the bounds
The integral approximation gives a tight estimate for the nth harmonic number.
For a lower bound, we obtain
Page 7
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 8
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Recurrence Relations:
A recurrence relation is an equation which is defined in terms of itself is called as recurrence
relation. Recurrence relation can be classified into following types-
Homogeneous recurrence relation
Non-homogeneous recurrence relation
Logarithmic recurrence relation
In this methods to solve the RR first find the roots of characteristic equations, and then generate the
solution according to following cases-
𝑇 (𝑛 ) = 𝐶1 𝑟1 𝑛 + 𝐶2 𝑟2 𝑛 + 𝐶3 𝑟3 𝑛 ….
𝑇 (𝑛 ) = 𝐶1 𝑟1 𝑛 + 𝐶2 𝑛𝑟2 𝑛 + 𝐶3 𝑛 2 𝑟3 𝑛 ….
𝑇 (𝑛 ) = 𝐶1 𝑟1 𝑛 + 𝐶2 𝑟2 𝑛 + (𝐶3 𝑟3 𝑛 + 𝐶4 𝑛𝑟4 𝑛 + 𝐶5 𝑛 2 𝑟5 𝑛 … . )
Page 9
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Where
𝑡(𝑛 ) − time complexity of n inputs
𝑎𝑛 − 𝑐𝑜𝑛𝑠𝑡𝑎𝑛𝑡 𝑡𝑒𝑟𝑚
𝑛 , 𝑖𝑓 𝑛 = 0 𝑜𝑟 𝑛 = 1
𝑡 (𝑛 ) = {
𝑡(𝑛 − 1) + 𝑡(𝑛 − 2) , 𝑜𝑡𝑒𝑟𝑤𝑖𝑠𝑒
Solution:
𝑡(𝑛 ) = 𝑡(𝑛 − 1) + 𝑡(𝑛 − 2)
𝑡(𝑛 ) − 𝑡(𝑛 − 1) − 𝑡(𝑛 − 2) = 0
𝑡(𝑛 ) = 𝐶1 𝑟1 𝑛 + 𝐶2 𝑟2 𝑛
∴ 𝑡(𝑛 ) = 𝐶1 (1.6180)𝑛 + 𝐶2 (−0.6180)𝑛 …… (1)
Page 10
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
𝐶1 = −0.447
From eqn (1)
If the recurrence is not constant and if contain different term vary differently according to time is
called as non homogenous recurrence relation.
Standard form
𝑡(𝑛 ) ± 𝑎0 𝑡(𝑛 − 1) ± 𝑎1 𝑡(𝑛 − 2) ± 𝑎2 𝑡(𝑛 − 3) ± ⋯ = 𝑏 𝑛 𝑝(𝑛)
Where
𝑡(𝑛 ) − time complexity of n inputs
𝑎𝑛 − 𝑐𝑜𝑛𝑠𝑡𝑎𝑛𝑡 𝑡𝑒𝑟𝑚
𝑏 𝑛 − 𝑒𝑥𝑝𝑜𝑛𝑒𝑛𝑡𝑖𝑎𝑙 𝑡𝑒𝑟𝑚
𝑝(𝑛 ) − 𝑝𝑜𝑙𝑦𝑛𝑜𝑚𝑖𝑎𝑙 𝑡𝑒𝑟𝑚
Example:
𝑡(𝑛 ) − 2𝑡(𝑛 − 1) − 3𝑡(𝑛 − 2) = 3𝑛 𝑛
Substitution method:
The substitution method for solving recurrences involves guessing the form of the solution and then
using mathematical induction to find the constants and show that the solution works. The name
comes from the substitution of the guessed answer for the function when the inductive hypothesis is ;
P0l./’; nbcnnmjhkol,,l2121papplied to smaller values. This method is powerful, but it obviously can
be applied only in cases when it is easy to guess the form of the answer.
The substitution method can be used to establish either upper or lower bounds on a recurrence. As an
example, let us determine an upper bound on the recurrence
Page 11
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Iteration method:
The method of iterating a recurrence doesn't require us to guess the answer, but it may require more
algebra than the substitution method. The idea is to expand (iterate) the recurrence and express it as a
summation of terms dependent only on n and the initial conditions. Techniques for evaluating
summations can then be used to provide bounds on the solution.
A recursion tree is useful for visualizing what happens when a recurrence is iterated. It diagrams the
tree of recursive calls and the amount of work done at each call.
For instance, consider the recurrence
The recursion tree for this recurrence has the following form:
In this case, it is straightforward to sum across each row of the tree to obtain the total work done at a
given level:
Page 12
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
This a geometric series, thus in the limit the sum is O(n2). The depth of the tree in this case does not
really matter; the amount of work at each level is decreasing so quickly that the total is only a
constant factor more than the root. Recurrence trees can be a good method of guessing.
Note that the tree here is not balanced: the longest path is the rightmost one, and its length is log3/2 n.
Hence our guess for the closed form of this recurrence is O(n log n).
Master theorems:
The master theorem applies to recurrence of the following form
𝑛
𝑇 (𝑛 ) = 𝑎𝑇 ( ) + 𝑓(𝑛)
𝑏
Where 𝑎 ≥ 1 , 𝑏 > 1 𝑎𝑟𝑒 𝑐𝑜𝑛𝑠𝑡𝑎𝑛𝑡𝑠 𝑎𝑛𝑑 𝑓(𝑛 ) 𝑖𝑠 𝑎𝑛 𝑎𝑠𝑦𝑚𝑝𝑡𝑜𝑡𝑖𝑐𝑎𝑙𝑙𝑦 𝑝𝑜𝑠𝑖𝑡𝑖𝑣𝑒 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛.
There are 3 cases-
𝑎−𝜖 𝑎
1. 𝑖𝑓 𝑓 (𝑛 ) = Ο( 𝑛 𝑙𝑜𝑔𝑏 ), 𝑓𝑜𝑟 𝑠𝑜𝑚𝑒 𝑐𝑜𝑛𝑡𝑎𝑛𝑡 𝜖 > 0 𝑡ℎ𝑒𝑛 𝑇 (𝑛 ) = θ( 𝑛 𝑙𝑜𝑔𝑏 )
𝑎 𝑎
2. 𝑖𝑓 𝑓 (𝑛 ) = θ( 𝑛 𝑙𝑜𝑔𝑏 ), 𝑡ℎ𝑒𝑛 𝑇(𝑛 ) = θ( 𝑛 𝑙𝑜𝑔𝑏 𝑙𝑜𝑔𝑛)
𝑎+𝜖
3. 𝑖𝑓 𝑓 (𝑛 ) = Ω( 𝑛 𝑙𝑜𝑔𝑏 ), 𝑓𝑜𝑟 𝑠𝑜𝑚𝑒 𝑐𝑜𝑛𝑡𝑎𝑛𝑡 𝜖 > 0 𝑡ℎ𝑒𝑛 𝑇 (𝑛 ) = θ(𝑓(𝑛) )
Example: find the complexity by using master theorems
𝑛
1. 𝑇 (𝑛 ) = 4𝑇 ( ) + 𝑛
2
𝑛
2. 𝑇 (𝑛 ) = 4𝑇 ( ) + 𝑛 2
2
𝑛
3. 𝑇 (𝑛 ) = 4𝑇 ( ) + 𝑛 3
2
𝒏
𝟏. (𝒏) = 𝟒𝑻 ( ) + 𝒏
𝟐
Solution:
𝑎=4
𝑏=2
𝑓(𝑛) = 𝑛
𝑎 4
𝑛 𝑙𝑜𝑔𝑏 = 𝑛 𝑙𝑜𝑔2 = 𝑛 2
𝑎
𝑛 𝑙𝑜𝑔𝑏 > 𝑓(𝑛 ) 𝑐𝑎𝑠𝑒1
𝑎
𝑇 (𝑛 ) = θ( 𝑛 𝑙𝑜𝑔𝑏 )
∴ 𝑻(𝒏) = 𝛉( 𝒏𝟐 )
Page 13
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
𝒏
𝟐. 𝑻(𝒏) = 𝟒𝑻 ( ) + 𝒏𝟐
𝟐
Solution:
𝑎=4
𝑏=2
𝑓(𝑛) = 𝑛 2
𝑎 4
𝑛 𝑙𝑜𝑔𝑏 = 𝑛 𝑙𝑜𝑔2 = 𝑛 2
𝑎
𝑛 𝑙𝑜𝑔𝑏 = 𝑓(𝑛 ) 𝑐𝑎𝑠𝑒2
𝑎
𝑇 (𝑛 ) = θ( 𝑛 𝑙𝑜𝑔𝑏 log 𝑛)
∴ 𝑻(𝒏) = 𝛉( 𝒏𝟐 𝒍𝒐𝒈𝒏 )
𝒏
𝟑. 𝑻(𝒏) = 𝟒𝑻 ( ) + 𝒏𝟑
𝟐
Solution:
𝑎=4
𝑏=2
𝑓(𝑛) = 𝑛 3
𝑎 4
𝑛 𝑙𝑜𝑔𝑏 = 𝑛 𝑙𝑜𝑔2 = 𝑛 2
𝑎
𝑛 𝑙𝑜𝑔𝑏 < 𝑓(𝑛 ) 𝑐𝑎𝑠𝑒3
𝑇 (𝑛 ) = θ( 𝑓(𝑛))
∴ 𝑻(𝒏) = 𝛉( 𝒏𝟑 )
Complexity is nothing but finding loop in the program. There are following loop are used as follow-
for loop:
Consider the following for loop
1. for( i=0 ; i<n ; i++)
{
a = b+c;
}
Complexity: O(n)
2. for( i=0 ; i<n ; i++)
{
for( j=0 ; i<m ; j++)
{
a = b+c;
}
}
Complexity: O(nm)
Page 14
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
3. 𝑙 = 0
for j=1 to n do
{
for i=1 to n2 do
{
for k=1 to n3 do
{
l =l+1;
}
}
}
Complexity : O( n *n2 *n3)
Sequence of
Input Output
instructions
Characteristics of an Algorithm:
There are following characteristics are
Input:
Zero or more quantities are externally supplied into algorithm are called input.
Outputs:
At least one quantity must be produced are called as outputs.
Definiteness:
Each instruction must be clear and unambiguous.
Finiteness:
It can be defined as the algorithms must be terminated after finite number of steps. Time
Of termination should be short
Effectiveness:
Page 15
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Area of Algorithm:
The process of determining its complexity in term of time or space is known as analysis of
algorithm.
4. Testing:
Expressing Algorithm:
o English
o Flow chart
o Pseudo code
Page 16
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Writing Algorithm:
Example: algorithm to find sum of array value A' and 'n' is the size of array
Algorithm Sum(A, n)
{
S=0
For i=1 to n do
S=S+A[i];
Return S;
}
Page 17
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT-I
Asymptotic Notation
TOPICS
1. Asymptotic notations of Analysis of Algorithms
2. Analyzing Control Structures
3. Worst case and Average case Analysis
4. Amortized analysis
5. Sorting networks
6. Comparison networks
7. Bio-tonic sorting network
8. Advanced data structures like
– Fibonacci heap
– Disjoint set representation
Page 18
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Asymptotic Notations:
Asymptotic Notation are mathematical tools to represent the time complexity of algorithm for
asymptotic analysis. It is also known as rate of growth.
There are following three asymptotic notation are mostly used to represent time complexity of
algorithm are-
Big-oh Notation(𝑂)
Omega Notation(Ω)
Theta Notation (𝜃)
Big-oh Notation(𝑶):
The 𝑂(𝑛) is the formal way to express the upper bound of an algorithm running time, it measures
the worst case time complexity or longest amount of time an algorithm can possibly take to
complete shown in fig.
Omega Notation(𝛀):
The Ω(𝑛) is the formal way to express the lower bound of an algorithm running time, it measures
the best case time complexity or best amount of time an algorithm can possibly take to complete
shown in fig.
Theta Notation(𝜽):
The 𝜃(𝑛) is the formal way to express the both lower bound and upper bound of an algorithm
running time, it measures the average case time complexity an algorithm can possibly take to
complete shown in fig.
The analysis of an algorithm refers as calculating individual instruction running time, instruction
running time can be calculated by analyzing control structures, there are following control structures
are-
Sequencing
If then else
For loop
While loop
Recursion
Sequencing:
Suppose an algorithm consist of two parts A and B.
A takes time 𝑡𝐴 and B takes time 𝑡𝐵 for computation. The total computation (𝑡𝐴 +𝑡𝐵 ) time is
calculated according to the sequencing rules is (max (𝑡𝐴 , 𝑡𝐵 ) )
Example:
Suppose 𝑡𝐴 = 𝑂(𝑛 ) 𝑎𝑛𝑑 𝑡𝐵 = 𝑂(𝑛 2 ) , calculate the total time computation as,
Computation time = 𝑡𝐴 +𝑡𝐵
= max (𝑡𝐴 , 𝑡𝐵 )
= max (𝑂(𝑛 ), 𝑂 (𝑛 2 ))
= 𝑂 (𝑛 2 )
If then else:
The total computation time is calculated according to the conditional rule “if-then else” is
max (𝑡𝐴 , 𝑡𝐵 )., shown in fig.
Page 20
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Condition
𝑡𝐴 = 𝑂(𝑛 2 ) A A 𝑡𝐵 = 𝜃(𝑛 3 )
{
P(ij)
}
}
𝑚 𝑛 𝑚 𝑛
Page 21
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
While loop:
Consider the example:
While ( n > 1)
{
P(i)
𝑛
𝑛=
2
}
Page 22
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
4. Amortized analysis:
:
Amortized analysis means finding the average running time per operation over a worst case sequence
of operations.
Amortized analysis assumes worst case input and typically does not allow random choice.
There are several techniques used in amortized analysis-
Aggregate methods:
In this method, we compute an upper bound T(n) on the total cost of a sequence of n operations.
Accounting method:
In this ,overcharge some operations early in the sequence this overcharge is used later in the
sequence for pay operation that charge less than they actually cost.
Potential method:
In this, maintain the credit as the potential energy to pay for future operation.
Example:
Define amortized analysis. Explain the amortized complexity for 4 bit binary incrementor from 0to 8
,and also write algorithm:
Solution:
Consider binary no. between 0 to 8
0 0000 0 cycle
1 0001 1
2 0010 2
3 0011 1
4 0100 3
Are consuming more cycle i.e.
5 0101 1
potential input
6 0110 2
7 0111 1
8 1000 4
a[ i ] = 1
Page 23
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
5. Sorting networks:
A :sorting networks is a comparison network for which output sequence is monotonically increasing
for every input sequence.
Sorting network is capable of sorting thousands of items in the order of microseconds and can be
constructed with present day hardware.
Advantage:
o It is a fast sorting capability can be used to manipulate large set of data.
o Capable of sorting thousands of item in order of microseconds.
6. Comparison networks:
Page 24
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1, 3, 5, 9,| 8, 7, 4, 2
1 1
3 2
5 3
9 4
8 5
7 7
4 8
2 9
Page 25
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Delete Min:
In this , we show how to decrease the key of a node in a Fibonacci heap in O(1) amortized time and
how to delete any node from an n-node Fibonacci heap in O(D(n)) amortized time. These operations
do not preserve the property that all trees in the Fibonacci heap are unordered binomial trees. They
are close enough, however, that we can bound the maximum degree D(n) by O(1g n). Proving this
bound will imply that FIB-HEAP-EXTRACT-MIN and FIB-HEAP-DELETE run in O(1g n)
amortized time.
Page 26
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
A disjoint-set data structure maintains a collection S = {S1, S2, . . . ,Sk} of disjoint dynamic sets.
Each set is identified by a representative, which is some member of the set. In some applications, it
doesn't matter which member is used as the representative; we only care that if we ask for the
representative of a dynamic set twice without modifying the set between the requests, we get the
same answer both times. In other applications, there may be a prespecified rule for choosing the
representative, such as choosing the smallest member in the set (assuming, of course, that the
elements can be ordered).
As in the other dynamic-set implementations we have studied, each element of a set is represented by
an object. Letting x denote an object, we wish to support the following operations.
MAKE-SET(x) creates a new set whose only member (and thus representative) is pointed to by x.
Since the sets are disjoint, we require that x not already be in a set.
UNION(x, y) unites the dynamic sets that contain x and y, say Sx and Sy, into a new set that is the
union of these two sets. The two sets are assumed to be disjoint prior to the operation. The
representative of the resulting set is some member of Sx Sy , although many implementations
of UNION choose the representative of either Sx or Sy, as the new representative. Since we require
Page 27
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
the sets in the collection to be disjoint, we "destroy" sets Sx and Sy , removing them from the
collection S.
FIND-SET(x) returns a pointer to the representative of the (unique) set containing x.
Throughout this chapter, we shall analyze the running times of disjoint-set data structures in terms of
two parameters: n, the number of MAKE-SET operations, and m, the total number of MAKE-
SET, UNION, and FIND-SET operations. Since the sets are disjoint, each UNION operation reduces
the number of sets by one. After n - 1 UNION operations, therefore, only one set remains. The
number of UNION operations is thus at most n - 1. Note also that since the MAKE-SET operations
are included in the total number of operations m, we have m n.
Page 28
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT -III
Divide and Conquer Strategies & Greedy
Approach
TOPICS:
1. Knapsack Problem
2. Application to Job Sequencing with Deadlines Problem
3. Minimum Cost Spanning Trees
4. Single Source Shortest Path
5. Optimal Merge Patterns.
Page 29
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
In divide and conquer approach, the problem is divided into smaller sub-problems and then each
problem is solved independently. The solution of all sub-problems is finally merged in order to
obtain the solution of an original problem.
We can understand divide-and-conquer approach in a three-step process.
Divide/Break:
This step involves breaking the problem into smaller sub-problems. This step generally takes a
recursive approach to divide the problem until no sub-problem is further divisible.
Conquer/Solve:
This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems
are considered 'solved' on their own.
Merge/Combine:
When the smaller sub-problems are solved, this stage recursively combines them until they formulate
a solution of the original problem.
There are following Algorithms are-
1. Binary search
3. Merge Sort
4. Quick Sort
5. Matrix Multiplication
Page 30
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. Binary search:
These Analysis is used to find average no. of comparison required for successful or unsuccessful
search.
To find average no of comparison by using
o Average no. of comparison for successful search
𝐼𝑃𝐿
𝐴𝑆 (𝑛 ) = +1
𝑛
o Average no. of comparison for unsuccessful search
𝐸𝑃𝐿
𝐴𝑢 ( 𝑛 ) =
𝑛+1
Where,
IPL (Internal Path Length):
It is the length of path for all node in a binary search node and search will be successful.
EPL (External Path Length):
It is the length of path for all node in a binary search node and search will be unsuccessful.
𝐄𝐏𝐋 = 𝐈𝐏𝐋 + 𝟐𝐧
𝐧 − no. of elements
Assumption:
A - Array of ‘n’ elements and sorted in ascending order
key – element to be search
low – lower index =1
high – upper index = n
Page 31
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm:
Algorithm Binsearch(A, key, low, high)
{
if ( low = = high )
{
if ( key = = A[low] )
return low;
else
return 0;
}
else
{
mid = ( low + high) /2
if ( key = = A[mid] )
return mid;
else
{
if ( key < A[mid] )
Binsearch(A, key, low, mid-1)
else
Binsearch(A, key, mid+1,high)
}
}
}
Complexity:
Best case: 𝑇 (𝑛 ) = 1, 𝑓𝑜𝑟 𝑛 = 1
Average and worst case:
𝑛
𝑇 (𝑛 ) = 𝑇 ( ) + 1, 𝑓𝑜𝑟 𝑛 ≥ 1
2
Recurrence Relation:
𝟏 , 𝒊𝒇 𝒏 = 𝟏
𝑻(𝒏) = { 𝑛
𝑇( )+ 1 , 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
2
𝑻(𝒏) = 𝑶(𝐥𝐨𝐠𝟐 𝒏)
Page 32
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm:
Algorithm Min_max( A, min, max, low, high)
{
if ( low = = high) then
{
min = max = A[low]
}
else
{
if ( low = high -1) then
{
if ( A[low] < A[high]) then
{
min = A[low]
max = A[high]
}
else
{
min = A[high]
max = A[low]
}
}
else
{
mid =( low + high) /2
Min_max( A, low, mid, min, max)
Min_max(A, mid+1, high, min, max)
}
}
Complexity: log2n
Page 33
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
3. Merge Sort:
In this algorithm, array divided into small size with single element
The divided array will be merge into single array by performing comparison between two elements.
Assumption:
Input: unsorted array A
Output: sorted array A
Algorithm:
Algorithm Mergesort( A, low, high)
{
if ( low < high)
{
mid =( low + high) /2
Mergesort( A, low, mid)
Mergesort( A, mid+1, high)
Merge ( A, low, mid, high)
}
}
Complexity: O(n log2n)
Where ‘n’ is the no of comparisons and log2 n is the height of tree.
Page 34
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
4. Quick Sort:
This sorting method is based on dividing the array on a key value and generating the position of key
value such that array will be divided into two parts and after divide the array position of key is fixed.
There are two conditions:
1. If (i < j) then interchange A[i] and A[j]
2. If (i ≥ j ) then interchange A[key] and A[j].
Page 35
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Complexity:
1. Best case & Average case - O (n log2n):
In quick sort when the elements is placed at proper position automatically. It most of the cases few
more elements is replace proper position. This will reduce the complexity of algorithm. Hence best
and average case complexity of quick sort is O (n log2n) where ‘n’ is the maximum no. of
comparison and log2n is no. of passes.
2. Worst case - O (n2 ):
in Quick sort ,if array is already sorted in descending order but require to arrange in ascending order
then after each passes the array generated will be (n-1) value is one part and only one value is
another part
with this approach the divide array size n,(n-1) operations will be required. Hence the complexity of
Quick sort in worst case is O (n2).
Page 36
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
2. Greedy Methods:
Among all the algorithmic approaches, the simplest and straightforward approach is the Greedy
method. In this approach, the decision is taken on the basis of current available information without
worrying about the effect of the current decision in future.
Greedy algorithms build a solution part by part, choosing the next part in such a way, that it gives an
immediate benefit. This approach never reconsiders the choices taken previously. This approach is
mainly used to solve optimization problems. Greedy method is easy to implement and quite efficient
in most of the cases. Hence, we can say that Greedy algorithm is an algorithmic paradigm based on
heuristic that follows local optimal choice at each step with the hope of finding global optimal
solution.
In many problems, it does not produce an optimal solution though it gives an approximate (near
optimal) solution in a reasonable time.
Areas of Application:
Finding the shortest path between two vertices using Dijkstra’s algorithm.
Finding the minimal spanning tree in a graph using Prim’s /Kruskal’s algorithm, etc.
Page 37
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. Knapsack Problem:
Knapsack is a bag of fixed capacity capable of storing certain objects.
The objects can be stored either completely or partially.
There are three different approaches for knapsack problem.
1. Select the objects with maximum Profit (P i).
2. Select the objects with minimum Weigh t(Wi).
3. Select the objects with maximum (Pi /Wi).
Assumption:
1. P[1….n] profit array
2. W[1…n] weight array
Capacity = total capacity
Weight = 0
x[1…n] is the array that contains three types of values
1 = complete
0 = reject
Fraction = partially
Algorithm Knapsack(P, W, capacity, weight)
Step1: For i = 1 to n do
x[i] = 0
weight = 0
Step2: while ( weight < capacity) do
{
Select the best object with max (Pi/ Wi) ratio, let its index = i
if (weight + W[i] <= capacity ) then
{
x[i] = 1
weight = weight +W[i]
}
else
{
𝑐𝑎𝑝𝑎𝑐𝑖𝑡𝑦−𝑤𝑒𝑖𝑔ℎ𝑡
x[i] =
𝑊[𝑖]
weight = capacity
}
Step3: Profit = 0
For i = 1 to n do
Profit = profit + [x[i]×P[i]]
}
Complexity: O( nlog n)
Page 38
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 39
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Assumption:
1. G is a graph which represented in the form of cost matrix of size n×n
2. Minimum cost = 0
3. There are two functions used in algorithm
1. Find:
These function will find the component in which the vertex are present.
2. Merge:
These function will merge the two component if they are different.
Page 40
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Prim’s algorithm:
o In this algorithm the Spanning Tree will be generated by selecting the edges with minimum
cost.
o The process is continue from one of vertices of the selected edge which leads to minimum
cost.
Page 41
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 42
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. In this, edge is selected with minimum In this, edge is selected with minimum value
value. and connectivity.
2. Graph generated with isolated and will Graph generated will be connected but no
required connecting edge inter path require.
Page 43
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
In this, Merge a set of sorted files of different length into a single sorted file. We need to find an
optimal solution, where the resultant file will be generated in minimum time.
If the number of sorted files are given, there are many ways to merge them into a single sorted file.
This merge can be performed pair wise. Hence, this type of merging is called as 2-way merge
patterns.
Page 44
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT -IV
Dynamic Programming
TOPICS:
1. Multistage graphs
2. All pairs shortest path
3. Single source shortest paths
4. Optimal binary search trees
5. Traveling salesman problem
6. Longest Common Subsequence problem
7. 0/1 Knapsack Problem
8. Chained Matrix Multiplication
Page 45
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. Multistage Graphs:
Principal:
In this method, Graph is divided into different stages that is stage-1 to stage-n and will have only one
vertex for each.
The main objective is to find shortest path between source and destination.
There are two methods are used-
Backward algorithm
Forward algorithm
Backward Algorithm:
In this method calculation for shortest path from source to destination the information about previous
stage is considered.
To find backward cost by using-
𝑏𝑐𝑜𝑠𝑡 (𝑖, 𝑗 ) = min { 𝑏𝑐𝑜𝑠𝑡 (𝑖 − 1, 𝐿 ) + 𝑐𝑜𝑠𝑡(𝐿, 𝑗 )}
Where, 𝑖 − 𝑠𝑡𝑎𝑔𝑒 𝑛𝑜.
𝑗 − 𝑁𝑜𝑑𝑒 /𝑉𝑒𝑟𝑡𝑒𝑥 𝑛𝑜.
𝑏𝑐𝑜𝑠𝑡 ( ) − 𝑛𝑜𝑑𝑒 𝑐𝑜𝑠𝑡
𝑐𝑜𝑠𝑡( ) − 𝑝𝑎𝑡ℎ 𝑐𝑜𝑠𝑡
Assumption:
1. Graph is represented in form of cost matrix size n×n
2. bcost[1…n] is used to store cost value
3. d[1…n] is used to store intermediate vertices
4. P[1…k] is path array and k is no of edges
Page 46
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Forward Algorithm:
In this method calculation of shortest path from destination to source the information about next
stage is consider
To find shortest path by using-
𝐹𝑐𝑜𝑠𝑡 (𝑖, 𝑗 ) = min{ 𝐹𝑐𝑜𝑠𝑡 (𝑖 + 1, 𝐿 ) + 𝑐𝑜𝑠𝑡(𝐽, 𝐿 )}
Where, 𝑖 − 𝑠𝑡𝑎𝑔𝑒 𝑛𝑜.
𝑗 − 𝑁𝑜𝑑𝑒 /𝑉𝑒𝑟𝑡𝑒𝑥 𝑛𝑜.
𝐹𝑐𝑜𝑠𝑡 ( ) − 𝑛𝑜𝑑𝑒 𝑐𝑜𝑠𝑡
𝑐𝑜𝑠𝑡( ) − 𝑝𝑎𝑡ℎ 𝑐𝑜𝑠𝑡
Page 47
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 48
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Dijktra’s Algorithm:
This Algorithm works with directed and undirected Graph with non negative edge weight.
Algorithm Dijkstra(G, s)
{
For each vertex v
Mark v as unvisited
and set d(v) = 1
Set d(s) = 0
while (there is unvisited vertex)
{
v = unvisited vertex with smallest d ;
Visit v, and Relax all its outgoing edges;
}
return d ;
}
Complexity: O (V2)
Page 49
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm Bellman-Ford(G, s)
{
For each v
Set d(v) = 1
Set d(s) = 0
for (k = 1 to |V|-1)
Page 50
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
for r = i to j do
{
t = E[i, r - 1] + E[r + 1, j] + W[i, j]
if (t < E[i, j])then
{
E[i, j] = t
root[i, j] = r
}
}
}
}
return E and root
o The main objective of this problem is to find shortest path from one source to all vertices and
travelling back to source.
o The path should be such that all the vertices are covered in minimum distance.
o The concept is applicable on directed and complete graph.
Page 51
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
If a set of sequences are given, the longest common subsequence problem is to find a common
subsequence of all the sequences that is of maximal length.
The longest common subsequence problem is a classic computer science problem, the basis of data
comparison programs such as the diff-utility, and has applications in bioinformatics. It is also widely
used by revision control systems.
Let X = < x1, x2, x3,…, xn > and Y = < y1, y2 , y3,…, ym > be the sequences. To compute the length of
an element the following algorithm is used.
Page 52
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
𝐷 = [𝑑0 , 𝑑1 , 𝑑2 , … , 𝑑𝑛 ]
2. Construction of Cost Matrix:
𝒎𝒊𝒏
𝑴 𝒊,𝒊+𝒔 = 𝒊≤𝒌<𝑖+𝑠 { 𝑴𝒊𝒌 + 𝑴𝒌+𝟏,𝒊+𝒔 + 𝒅𝒊−𝟏 ∗ 𝒅𝒌 ∗ 𝒅𝒊+𝒔 }
3. Find optimal sequence
Page 53
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 54
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 55
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT V
Syllabus
Basic traversal and search technique
1. Breadth first search (BFS)
2. Depth first search (DFS)
Backtracking basic strategy
1. N- Queen’s problem
2. Graph coloring
3. Hamiltonian cycle
4. Sum of subset
5. Introduction to approximation algorithms
Page 56
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Introduction:
Graph and trees required searching for a node with some specific properly. When the search require
necessarily visiting every node in the structure, then it called as traversal
One of the most fundamental graph problems is to traverse every edge and vertex in the graph.
There are following techniques are used-
1. Breadth first search (BFS)
2. Depth first search (DFS)
Page 57
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 58
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 59
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Bi-connectedGraph:
Bi-connected graph has edges that are “two way” ie. We can go from one vertex to another and vice-
versa.
A Bi-connected graph is a connected and “non seprable” graph meaning that if any vertex to be
removed the graph will remain connected
Bi-connected graph has no articulation point
Bi- connected graph, if in a graph there is no AP then it is called is connected graph. ie. it is by
connected component which is entire graph.
1 2
5 4
Page 60
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Articulation point:
Represent a vertex in a graph such that if it is remove then graph is divided into 2 or more sub graph
this vertex is called as articulation point.
It is require to find AP then the principle of DFS is used.
1 AP 5
4 2 7
3 8
10
9
Method:
To find out articulation point on the graph perform DFS & generate a sequence representing the
order in which nodes are visited.
4 6 7
3 5 8
10 9 2
Sequence: 1-4-3-10-9-2-5-6-7-8
From the generated sequence draw a tree called DFS Tree in which the vertex is visited will decide
the position of vertex in the tree.
Page 61
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Tree edge:
If the edge is given in the graph & also present in generated tree then it is called as tree edge.
Back edge:
If the edge is present in the graph but not present in the generated tree then it is called as back edge
shown as (…………)
Forward edge:
Forward edges are those edge non tree edge (u,v) connecting a vertex u to descendent v in depth first
tree
Cross edge:
Cross edges are other edges they can go between vertices in the same DFS, as long as on vertex is
not an ancestor of the other, or they can go between verttices in different DFS
Rules:
If a vertex act as an intermediate in a connection using back edge ancestor, parent & child then
vertex must be an articulation point
A
1
P
10
9 2
6
7
8
C
The root node can be consider as AP if the degree of root node is 2 or more in the graph.
Page 62
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
2. Backtracking:
Backtracking is a systematic way to go through all possible configuration of search space.
: basic idea of backtracking is build up a vector one component at a time and to test whether the
The
vector being formed has any chance of success.
:
Backtracking algorithm is that if it is realized that the partial vector generated does not lead to an
:
optimal solution then that vector may be ignored.
In:this method input is provided in the form of different component present in one set
: example:
For
Input X = { x1, x2, x3,………… xn}
X = Card deck then xn =52
The solution is generated by the reorganize in the given i/p with respect to certain constraints.
For example:
Output Y = { y1, y2, y3,………… yn}.
There are two types of constraints
1. Explicit constraints.
2. Implicit constraints
1. Explicit constraints:
If any condition is specifically specified in a given problem then it is called as explicit constraints
(given constraints)
2. Implicit constraints:
If the condition is derived from the given problem it is called as implicit constraints.
Note that:
The most important aspect of backtracking is to define the constraints. There is no process involve
between input and output, we have organize all input to get the output
There are following problem based on backtracking:
1. N- Queen’s problem
2. Graph coloring
3. Hamiltonian cycle
4. Sum of subset
5. Introduction to approximation algorithm
Page 63
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1. N- Queen’s problem:
In N-Queen’s problem to define the constraints are-
Explicit constraints:
Chess board n× n is given in the problem where ‘n’ is the number of Queen’s
Implicit constraints:
1. No two Queen’s should be in same row
2. No two Queen’s should be in same column
3. No two Queen’s should be in same diagonally
There are two types of problems:
4- Queen’s problem
8- Queen’s problem
1. 4- Queen’s problem:
First define the constraints
Explicit constraints:
Chess board 4× 4 is given in the problem where ‘4’ is the number of Queen’s
Implicit constraints:
1. No two Queen’s should be in same row
2. No two Queen’s should be in same column
3. No two Queen’s should be in same diagonally
Possible solutions:
Solution 1
- Q1 - -
- - - Q2
Q3 - - -
- - Q4 -
Sequence x[2, 4, 1, 3 ]
Page 64
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Solution 2
- - Q1 -
Q2 - - -
- - - Q3
- Q4 - -
Sequence x[3, 1, 4, 2 ]
2. 8- Queen’s problem:
First define the constraints
Explicit constraints:
Chess board 8× 8 is given in the problem where ‘8’ is the number of Queen’s
Implicit constraints:
1. No two Queen’s should be in same row
2. No two Queen’s should be in same column
3. No two Queen’s should be in same diagonally
Possible solutions:
Solution 1
- - - Q1 - - - -
- - - - - Q2 - -
- - - - - - - Q3
- Q4 - - - - - -
- - - - - - Q5 -
Q6 - - - - - - -
- - Q7 - - - - -
- - - - Q8 - - -
Sequence x[4, 6, 8, 2, 7, 1, 3, 5]
Page 65
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Solution 2
- - - - Q1 - - -
- - Q2 - - - - -
Q3 - - - - - - -
- - - - - Q4 -
- Q5 - - - - - -
- - - - - - - Q6
- - - - Q7 - -
- - - Q8 - - - -
Sequence x[5, 3, 1, 7, 2, 8, 6, 4]
Page 66
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm N-queen( k, n)
{
For i = 1 to n do
{
if Place (k, i) then
X[k] = i
if ( k= n) then
Write ( x[1…..n])
else
N-queen(k +1, n)
}
}
Algorithm Place(k, i)
{
it is proposed to place k th queen in i th column
for j = 1 to k -1 do
{
if (x[j] = i) or
(abs (x[j] = abs( j – k))
return (false)
else
return (true)
}
}
k- row no or queen no
i- column
Complexity : O(k).
Page 67
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
2. Graph coloring:
In a given graph G (V, E). It is required to color vertices to the fixed number of color. Such that
1. No two adjacent vertices should be same color.
2. Number of color used should not exceed the given number of color.
Constraints:
1. Explicit constraints:
Fixed number of color
2. Implicit constraints:
Connected vertices should not be the same color.
Chromatic number (K):
The chromatic number of a graph is the smallest number of colors needed to color the vertices so that
no two adjacent vertices be the same color.
Chromatic number is represent the minimum number of color used to color the graph
Solution space tree:
These tree will define all the possible solution which can exist for a given graph and number of color
Example:
Consider a graph and implement graph coloring of all possible condition
1 2
4 3
Solution:
Number of vertices = 4
Number of color used =
Chromatic number (K) = d + 1 = 2 +1 = 3
Page 68
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
G
C1 C3
C2
1 1 1
C2
C3
2 2
C2
C1 C1
C3
3 3 3 3
C2 C2 C2 C3 C3
C3
4 4 4 4 4 4
Interchange c1 c2
C2
C1
C3
2 2
C1
C2 C2
C3
3 3 3 3
C1 C1 C1 C3 C3
C3
4 4 4 4 4 4
Page 69
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Interchange c2 c3
C3
C1
C2
2 2
C1
C3 C3
C2
3 3 3 3
C1 C1 C1 C2 C2
C2
4 4 4 4 4 4
Page 70
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm:
Algorithm Mcoloring(k)
{
do
{
x[k] = Getnode color(k)
if( x[k] == 0)
return
if( k == n) then
write( x[ 1-n])
else
Mcoloring(k+1)
}
while(true)
}
Algorithm Getnode color(k)
{
do
{
x[k] = [x[k] + 1] mod (m + 1)
//next higher color
if (x[k] == 0)
then return // all color restricted
for( j = 1; j< n; j++)
{
if (G[k, j] ≠ && x[k] ==x[j])
// same color
break
}
}
}
Page 71
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Plannar Graph:
A graph is plannar if it can be drawn such that no edges cross when drawn on plane surface. A map,
used by geographers can be easily converted to plannar graph.
3. Hamiltonian cycle:
It is a cycle generated on undirected graph and it is required to start from particular vertex and end
that same vertex and visiting all vertices exactly once. If edge is used is not repeated again.
Application:
1. Hamiltonian cycle is used to cryptography method.
2. It is used for circuit testing
Constraints:
Explicit constraints:
Starting and ending vertex is same
Implicit constraints:
1. No repetition of edge is allowed.
2. If the vertex is already visited then it will be available in previously generated sequence and it
cannot be used again.
Condition:
1. In last vertex should have connected to first vertex.
2. If the vertex is referred and position k then it not should present 1 to k-1.
3. There should be edge between vertex k – 1 and k
Page 72
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Example:
Apply the Hamiltonian cycle for the following graph
1 2 3 4
8 7 6 5
Solution:
Cycle 1:
1-2-8-7-6-5-4-3-1
Cycle 2:
1-7-8-6-5-4-3-2-1
Cycle 3:
1-3-4-5-6-7-8-2-1
Page 73
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Algorithm:
Algorithm HCycle(k)
{
do
{
Next value (k)
if ( x[k] = 0) then
Return
if ( k = n)
write (1-----n)
else
HCycle(k + 1)
}
while(true)
}
Complexity: O(nn)
Page 74
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
4. Sum of Subset:
It is a method by which a given array and a given integer operation is performed such that elements
are extracted from the array whose sum is equal to the given integer.
Constraints:
Explicit constraints:
Only given value should be used and summation should be equal to given sum.
Implicit constraints:
If an element ai is used then next element should be ai+1
There are two methods:
1. Variable size
2. Fixed size
Page 75
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 76
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 77
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Example
a d
b f g
c h
Page 78
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
a d
b f g
c h
Fig.(b) MST
a d
b f g
c h
a d
b f g
c h
Fig.(d) preorder sequence gives a tour
Page 79
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
RTMNU QUESTIONS:
1. Let W = {11,13,7,24} and m = 31. Find all possible subset of W that generate sum = m and draw
fixed size and variable size tuple solution space tree for same [w-10].
2. For the following graph, design Hamiltonian cycle. Write the algorithm for same. Explain how
: solution may result in multiple solutions.[w-10]
one
:
1 2 3 4
:
:
6
:
9 8 7 5
3. What is planner graph? implement graph coloring on the following graph and generate the solution
space tree if number of permitted colors = 3 give algorithm for graph coloring
[w-10, s-11,s-12]
1 2
4 3
4.Write an algorithm to solve 8 queens problem. Explain explicit constraints and implicit constraints
associated with this problem. Give at least 2 solutions for this problem.
[s-11,w-11,s-12,w-12,w-13, s-14]
5. What is backtracking? Explain the application in which backtracking principal can be used to
design solution. [s-11]
6. What is use of Hamiltonian Cycle? Implement cycle on following graph.[s-11,w-11,w-13]
Page 80
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1 2 3 4
8 7 6 5
7. What is bi-connected graph? find articulation point for the following graph.[w-11]
1 7
2 3 8
4 9
5
6
8. Implement Hamiltonian cycle on the following graph. generate at least two cycle. Write algorithm
for same.[w-12,s-12]
Page 81
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
1 2 3 4
8 7 6 5
9. Draw the solution space tree for fixed size tuple and variable size tuple for following array and
positive integer.
a = [12,16,9,25,10] sum = 35.
Find out solution node. [w-12]
9. Find out articulation point in the following graph. explain the procedure to find articulation point.
[w-12,s-14]
1 5
4 2 7
3 8
10
9
10. What is optimal vertex cover problem? Implement the problem on following graph to find out the
suitable vertex cover write algorithm.[s-13]
Page 82
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
A C E
D F
B
11. With respect to DFS, define Tree edge, Back edge, Forward edge, Cross edge. In DFS of an
undirected graph G. prove that every edge of G is either a free edge a back edge.[s-12]
12. Explain articulation point in DFS and give the complete algorithm for finding articulation point
of undirected graph.[w-13]
13. Explain approximation algorithm. Write an algorithm for vertex cover problem using
approximation principle.[w-13]
14. Design a solution for Hamiltonian path, explain how the solution can be used to solve
Hamiltonian cycle problem.[s-14].
Page 83
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
UNIT-VI
NP problems
Introduction to NP problem:
Many computer science problems are covered by the class NP. In particular, the decision versions of
many interesting search problems and optimization problems are contained in NP.
NP principle based on the concepts of Problem and Algorithm.
1. Classification of problems:
In computer science problems are classified in to following types-
1. Decision problem
2. Optimization problem
3. Search problem
4. Counting problem
5. Function problem
1. Decision problem:
Any problem for which the answer is either yes or no depending on the values of some input
parameter is called decision problem. Instead of yes/no sometimes it is also uses true/false,
success/failure as a output. Output of decision problem are Boolean. The input parameters can be
natural numbers as well as strings o formal languages.
Input
Algorithm
Yes No
Example: Give two n umbers x and y , does x divided by y is a decision problem. Because the
answer can be either yes or no depending upon value of x and y.
2. Optimization problem:
The problem of finding the best solution from all feasible solution is an optimization problem, it
involves the identification of optimal solution ie. Either maximum or minimum.
Example:
Finding chromatic number is the optimization problem.
Page 84
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
3. Search problem:
The process of finding particular elements from given problem domain is referred as search problem
Example:
Linear and binary search problems.
4. Counting problem:
The task of finding the number of elements of some set with a particular property.
Example:
Such counting problems are usually encountered in combinatorics.
5. Function problem:
In computational complexity theory, a function problem is a computational problem where a single
output (of a total function) is expected for every input, but the output is more complex than that of a
decision problem. For function problems, the output is not simply 'yes' or 'no'.
Example: Travelling seals man problem.
2. Classification of Algorithms:
Result return by the algorithm may be defined or may not be defined uniquely based on the
following factors-
1. Deterministic Algorithm
2. Non deterministic Algorithm
1. Deterministic Algorithm:
A Deterministic algorithm behaves as expected about the result of every operation of algorithm.
Deterministic algorithm always produces the same output and the machine will always pass through
the same sequence of states.
2. Verifying stage:
An deterministic algorithm takes both instances and input S, and checks whether S satisfied or not. It
returns success or failure.
Page 85
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 86
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Page 87
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Cook’s Theorem:
The theorem can be states that-
o Any NP problem can be converted to SAT in polynomial time.
o C-SAT is NP- complete.
o Satisfiability is NP complete.
Prove that P ⊆ NP , Also explain any three difference between P and NP.
ANS:
o The class of P problem is sub- class of NP problems because a problem in P can be solved in
polynomial time without given any certificate.
o NP-type problem is trying to solve (verifiable) in polynomial time thus P ⊆ NP
Difference between P and NP
P NP
Page 88
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
Analysis
Max-Clique problem is a non-deterministic algorithm. In this algorithm, first we try to determine a
set of k distinct vertices and then we try to test whether these vertices form a complete graph.
There is no polynomial time deterministic algorithm to solve this problem. This problem is NP-
Complete.
Example:
Take a look at the following graph. Here, the sub-graph containing vertices 2, 3, 4 and 6 forms a
complete graph. Hence, this sub-graph is a clique. As this is the maximum complete sub-graph of the
provided graph, it’s a 4-Clique.
Page 89
Notes Prepared By. Ahmad Sir
Contact: 9867597554
PERFECT ENGINEERING CLASSES
Contact: S-54,Utkarsh Nirmaan Complex, Mangalwari, Sadar, Nagpur
If problem B can be solved in polynomial time then problem A can be solved in polynomial time
If there is no polynomial-time algorithm to solve A then there is no polynomial-time algorithm to
solve B
We have reduced problem A to problem B.
Definition:
We can say that a decision problem A is polynomially many-one reducible to problem B (A<=B) if
there exists a function f computable in polynomial time that:
maps every instance x of A to an instance f(x) of B and
x is a yes-instance of A if and only if f(x) is a yes-instance of B.
Page 90
Notes Prepared By. Ahmad Sir
Contact: 9867597554