CS 6402 - Design and Analysis of Algorithm
CS 6402 - Design and Analysis of Algorithm
CS 6402 - Design and Analysis of Algorithm
UNIT I INTRODUCTION
Fundamentals of algorithmic problem solving – Important problem types – Fundamentals of the analysis
of algorithm efficiency – analysis frame work –Asymptotic notations – Mathematical analysis for
recursive and non-recursive algorithms.
PART A
1. What is an algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining a required
output for any legitimate input in finite amount of time.
An algorithm is step by step procedure to solve a problem.
3. What is the formula used in Euclid’s algorithm for finding the greatest common divisor of two
numbers?
Euclid‘s algorithm is based on repeatedly applying the equality
Gcd(m,n)=gcd(n,m mod n) until m mod n is equal to 0, since gcd(m,0)=m.
4. What are the three different algorithms used to find the gcd of two numbers?
The three algorithms used to find the gcd of two numbers are
Euclid‘s algorithm
Consecutive integer checking algorithm
Middle school procedure
7. What is pseudocode?
A pseudocode is a mixture of a natural language and programming language constructs to specify an
algorithm. A pseudocode is more precise than a natural language and its usage often yields more
concise algorithm descriptions.
A function t(n) is said to be in θ (g(n)), denoted by t(n) ε θ (g(n)), if t(n) is bounded both above & below
by some constant multiple of g(n) for all large n, i.e., if there exists some positive constants c1 & c2
and some nonnegative integer n0 such that
CS 6402 -Design And Analysis of Algorithm
c2g (n) <= t (n) <= c1g (n) for all n >= n0
22. Mention the useful property, which can be applied to the asymptotic notations and its use?
If t1(n) ε O(g1(n)) and t2(n) ε O(g2(n)) then t1(n)+t2(n) ε max {g1(n),g2(n)} this property is also true for
Ω and θ notations. This property will be useful in analyzing algorithms that comprise of two
consecutive executable parts.
23. What are the basic asymptotic efficiency classes?
The various basic efficiency classes are
Constant : 1
Logarithmic : log n
Linear : n
N-log-n : nlog n
Quadratic : n2
Cubic : n3
Exponential : 2n
Factorial : n!
24. What is algorithm visualization?
Algorithm visualization is a way to study algorithms. It is defined as the use of images to convey
some useful information about algorithms. That information can be a visual illustration of algorithm‘s
operation, of its performance on different kinds of inputs, or of its execution speed versus that of other
algorithms for the same problem.
PART B
1. Explain about algorithm with suitable example (Notion of algorithm).
An algorithm is a sequence of unambiguous instructions for solving a computational
problem, i.e., for obtaining a required output for any legitimate input in a finite amount of time.
Problem
Algorithm
COMPUTER
Input Output
Step3: Divide n by t. If the remainder of this division is 0, return the value of t as the answer
and stop; otherwise, proceed to Step4.
Step4: Decrease the value of t by 1. Go to Step2.
3. Discuss important problem types that you face during Algorithm Analysis.
sorting
Rearrange the items of a given list in ascending order.
Input: A sequence of n numbers <a1, a2, …, an>
Output: A reordering <a´1, a´2, …, a´n> of the input sequence such that a´1≤a´2
≤… ≤a´n.
A specially chosen piece of information used to guide sorting. I.e., sort student
records by names.
Examples of sorting algorithms
Selection sort
CS 6402 -Design And Analysis of Algorithm
Bubble sort
Insertion sort
Merge sort
Heap sort …
The algorithm runs the fastest among all possible inputs of size n.
Average case:
Efficiency (#of times the basic operation will be executed) for a
typical/random input of size n.
NOT the average of worst and best case
M(n) ∈ Θ (n)
Analysis:
CS 6402 -Design And Analysis of Algorithm
For sequential search, best-case inputs are lists of size n with their first elements equal to a search key;
accordingly,
Cbw(n) = 1.
Under these assumptions- the average number of key comparisons Cavg(n) is found as follows.
In the case of a successful search, the probability of the first match occurring in the i th position of
the list is p / n for every i, and the number of comparisons made by the algorithm in such a situation is
obviously i. In the case of an unsuccessful search, the number of comparisons is n with the probability of
such a search being (1- p). Therefore,
For example, if p = 1 (i.e., the search must be successful), the average number of key comparisons made
by sequential search is (n + 1) /2; i.e., the algorithm will inspect, on average, about half of the list's elements.
If p = 0 (i.e., the search must be unsuccessful), the average number of key comparisons will be n because the
algorithm will inspect all n elements on all such inputs.
= 2n-1
CS 6402 -Design And Analysis of Algorithm
UNIT II
Divide and conquer methodology – Merge sort – Quick sort – Binary search – Binary tree traversal
– Multiplication of large integers – Strassen‘s matrix multiplication – Greedy method – Prim‘s
algorithm – Kruskal‘s algorithm – Dijkstra‘s algorithm.
PART A
to‘k‘ distinct susbsets, 1<k <n, yielding ‗k‘ subproblems. The subproblems must be solved, and then a
method must be found to combine subsolutions into a solution of the whole. If the subproblems are still
relatively large, then the divide-and conquer strategy can possibly be reapplied.
7. Define of feasibility
A feasible set (of candidates) is promising if it can be extended to produce not merely a solution, but an
optimal solution to the problem.
4. Compute the desired submatrices r, s, t, u of the result matrix C by adding and/or subtracting various
combinations of the Pi matrices, using only Θ(n2) scalar additions and subtractions.
PART B
1. Explain Divide And Conquer Method
The most well known algorithm design strategy is Divide and Conquer Method. It
Divide the problem into two or more smaller subproblems.
Conquer the subproblems by solving them recursively.
Combine the solutions to the subproblems into the solutions for the original problem.
Divide and Conquer Examples
Sorting: mergesort and quicksort
Tree traversals
Binary search
Matrix multiplication-Strassen‘s algorithm
CS 6402 -Design And Analysis of Algorithm
ALGORITHM Mergesort(A[0..n-1])
//Sorts an array A[0..n-1] by recursive mergesort
//Input: An array A[0..n-1] of orderable elements
//Output: Array A[0..n-1] sorted in nondecreasing order if n
>1
copy A[0..(n/2)-1] to B[0..(n/2)-1]
copy A[(n/2)..n-1] to C[0..(n/2)-1]
Mergesort(B[0..(n/2)-1])
Mergesort(C[0..(n/2)-1]) Merge(B,C,A)
Divide: Partition array A[l..r] into 2 subarrays, A[l..s-1] and A[s+1..r] such that each element of
the first array is ≤A[s] and each element of the second array is ≥ A[s]. (Computing the index of s is
part of partition.)
Implication: A[s] will be in its final position in the sorted array.
Conquer: Sort the two subarrays A[l..s-1] and A[s+1..r] by recursive calls to quicksort
Combine: No work is needed, because A[s] is already in its correct place after the partition is
done, and the two subarrays have been sorted.
Steps in Quicksort
Select a pivot w.r.t. whose value we are going to divide the sublist. (e.g., p = A[l])
Rearrange the list so that it starts with the pivot followed by a ≤ sublist (a sublist whose elements
are all smaller than or equal to the pivot) and a ≥ sublist (a sublist whose elements are all greater
than or equal to the pivot ) Exchange the pivot with the last element in the first sublist(i.e., ≤
sublist) – the pivot is now in its final position
Sort the two sublists recursively using quicksort
ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r
//Output: The subarray A[l..r] sorted in nondecreasing order
if l < r
s Partition (A[l..r]) // s is a split position
Quicksort(A[l..s-1])
Quicksort(A[s+1..r]
ALGORITHM
BinarySearch(A[0..n-1], K)
//Implements nonrecursive binary search
//Input: An array A[0..n-1] sorted in ascending order and
// a search key K
//Output: An index of the array‘s element that is equal to K
// or –1 if there is no such element
l 0, r n–1
CS 6402 -Design And Analysis of Algorithm
Tour Cost
a→b→c→d→a 2+3+7+5 = 17
a→b→d→c→a 2+4+7+8 = 21
a→c→b→d→a 8+3+4+5 = 20
a→c→d→b→a 8+7+4+2 = 21
a→d→b→c→a 5+4+3+8 = 20
a→d→c→b→a 5+7+3+2 = 17
Efficiency: Θ((n-1)!)
7. Explain in detail about knapsack problem.
Given n items:
weights: w1 w2 … wn
values: v1 v2 …
vn a knapsack of
capacity W
Find most valuable subset of the items that fit into the knapsack
Example: Knapsack capacity
W=16 item weight value
1 2 $20
2 5 $30
3 10 $50
4 5 $10
Subset Total weight Total value
{1} 2 $20
{2} 5 $30
{3} 10 $50
{4} 5 $10
{1,2} 7 $50
{1,3} 12 $70
{1,4} 7 $30
CS 6402 -Design And Analysis of Algorithm
{2,3} 15 $80
{2,4} 10 $40
{3,4} 15 $60
{1,2,3} 17 not feasible
{1,2,4} 12 $60
{1,3,4} 17 not feasible
{2,3,4} 20 not feasible
{1,2,3,4} 22 not feasible
Efficiency: Θ(2^n)
UNIT – III
Computing a Binomial Coefficient – Warshall‟s and Floyd‟ algorithm – Optimal Binary Search Trees –
Knapsack Problem and Memory functions. Greedy Technique– Prim‟s algorithm- Kruskal's Algorithm-
Dijkstra's Algorithm- Huffman Trees.
PART A
1. Define dynamic programming.
Dynamic programming is an algorithm design method that can be used when a solution to the
problem is viewed as the result of sequence of decisions.
Dynamic programming is a technique for solving problems with overlapping subproblems. These sub
problems arise from a recurrence relating a solution to a given problem with solutions to its smaller
sub problems only once and recording the results in a table from which the solution to the original
problem is obtained. It was invented by a prominent U.S Mathematician, Richard Bellman in the 1950s.\
6. Write the difference between the Greedy method and Dynamic programming.
Greedy method
1. Only one sequence of decision is generated.
2. It does not guarantee to give an optimal solution always.
CS 6402 -Design And Analysis of Algorithm
Dynamic programming
1. Many number of decisions are generated.
2. It definitely gives an optimal solution always.
sequence of locally optimal choices will yield a globally optimal solution to the entire
problem. The choice must be made as follows.
Feasible: It has to satisfy the problem‘s constraints.
Locally optimal: It has to be the best local choice among all feasible choices available on that step.
Irrevocable : Once made, it cannot be changed on a subsequent step of the algorithm
14. How are the vertices not in the tree split into?
The vertices that are not in the tree are split into two sets
Fringe : It contains the vertices that are not in the tree but are adjacent to atleast one tree vertex.
Unseen : All other vertices of the graph are called unseen because they are yet to be affected by
the algorithm.
15. What are the operations to be done after identifying a vertex u* to be added to the tree?
After identifying a vertex u* to be added to the tree, the following two operations need to be performed
Move u* from the set V-VT to the set of tree vertices VT.
For each remaining vertex u in V-VT that is connected to u* by a shorter edge than the u‘s
current
distance label, update its labels by u* and the weight of the edge between u* and u, respectively.
PART B
1. Write Short note on Dijkstra's Algorithm Shortest Paths – Dijkstra’s Algorithm Shortest Path
Problems
o All pair shortest paths (Floy‘s algorithm)
o Single Source Shortest Paths Problem (Dijkstra‘s algorithm): Given a weighted graph G, find
the
shortest paths from a source vertex s to each of the other vertices.
create a cycle
1. at each stage the edge may:
2. expand an existing tree
3. combine two existing trees into a single tree
4. create a new tree
iv. need efficient way of detecting/avoiding cycles
algorithm stops when all vertices are included
ALGORITHM Kruscal(G)
//Input: A weighted connected graph G = <V, E>
//Output: ET, the set of edges composing a minimum spanning tree of G.
Sort E in nondecreasing order of the edge weights
w(ei1) <= … <= w(ei|E|)
ET ; ecounter 0 //initialize the set of tree edges and its size
k 0
while encounter < |V| - 1 do
k k+1
if ET U {eik} is acyclic
ET ET U {eik} ; ecounter ecounter + 1
return ET
adding the minimum weight edge connecting a vertex in tree (Ti) to one not yet in tree
choose from ―fringe‖ edges
CS 6402 -Design And Analysis of Algorithm
f(n-1) =
f(n) = f(n-1) + f(n-2)
ALGORITHM Fib(n)
F[0] 0, F[1] 1
for i2 to n do
F[i] F[i-1] + F[i-2]
return F[n]
CS 6402 -Design And Analysis of Algorithm
Main idea: Use a bottom-up method to construct the transitive closure of a given digraph with n
vertices through a series of nxn boolean matrices:
0 0 1 0
0 0 1 0 0 0 1 0
1 0 0 1 1 0 1 1
1 0 1 1
0 0 0 0 0 0 0 0
R(0) 0 0 0 0
0 1 0 0 1 1 1 1
0 1 0 0
Allow 1,2 to be an
Does not allow an R (2)
R (1) intermediate node
intermediate node Allow 1 to be an
intermediate node
R(3) R(4)
0 0 1 0 0 0 1 0
1 0 1 1 1 1 1 1
0 0 0 0 0 0 0 0
(3)
R
1 1 1 1 1 1 1 1
2 (4)
Allow 1,2,3 to be an intermediate Allow
R 1,2,3,4 to be an
node intermediate node
CS 6402 -Design And Analysis of Algorithm
In the kth stage: to determine R(k) is to determine if a path exists between two vertices i, j using
just vertices among 1,…,k
value
MFKnapsack(i – 1, j)
else
value max(MFKnapsack(i – 1, j),
values[I] + MFKnapsck( i – 1, j – Weights[i]))
V[i, j]
value
return V[i, j]
10. Explain in detail about Huffman tree.
Any binary tree with edges labeled with 0‘s and 1‘s yields a prefix-free code of characters assigned to its
leaves. Optimal binary tree minimizing the average length of a codeword can be constructed as follows:
Huffman’s algorithm
Initialize n one-node trees with alphabet characters and the tree weights with their frequencies.
Repeat the following step n-1 times: join two binary trees with smallest weights into one (as
left and right subtrees) and make its weight equal the sum of the weights of the two trees.
Mark edges leading to left and right subtrees with 0‘s and 1‘s, respectively.
CS 6402 -Design And Analysis of Algorithm
Example:
CS 6402 -Design And Analysis of Algorithm
UNIT IV
ITERATIVE IMPROVEMENT
The Simplex MeFthod-The Maximum-Flow Problem – Maximum Matching in Bipartite Graphs- The Stable marriage
Problem.
PART A
Let X be a set of vertices in a network that includes its source but does not include its sink, and let X, the
complement of X, be the rest of the vertices including the sink. The cut induced by this partition of the
vertices is the set of all the edges with a tail in X and a head in X.
Capacity of a cut is defined as the sum of capacities of the edges that compose the cut.
We‘ll denote a cut and its capacity by C(X,X) and c(X,X)
Note that if all the edges of a cut were deleted from the
network, there would be no directed path from source to sink
Minimum cut is a cut of the smallest capacity in a given network
CS 6402 -Design And Analysis of Algorithm
PART B
Simplex method:
Step 0 [Initialization] Present a given LP problem in standard form and set up initial tableau.
Step 1 [Optimality test] If all entries in the objective row are nonnegative — stop: the tableau represents
an optimal solution.
Step 2 [Find entering variable] Select (the most) negative entry in the objective row. Mark its column to
indicate the entering variable and the pivot column.
Step 3 [Find departing variable] For each positive entry in the pivot column, calculate the θ-ratio by
dividing that row's entry in the rightmost column by its entry in the pivot column. (If there are no
positive entries in the pivot column — stop: the problem is unbounded.) Find the row with the smallest
θ-ratio, mark this row to indicate the departing variable and the pivot row.
Step 4 [Form the next tableau] Divide all the entries in the pivot row by its entry in the pivot column.
Subtract from each of the other rows, including the objective row, the new pivot row multiplied by the
entry in the pivot column of the row in question. Replace the label of the pivot row by the variable's
name of the pivot column and go back to Step 1.
maximize z = 3x + 5y + 0u + 0v
subject to x+ y+ u =
4
x + 3y + v =6
x≥0, y≥0, u≥0, v≥0
CS 6402 -Design And Analysis of Algorithm
Definition of flow:
CS 6402 -Design And Analysis of Algorithm
A flow is an assignment of real numbers xij to edges (i,j) of a given network that satisfy the following:
flow-conservation requirements: The total amount of material entering an intermediate vertex
must be equal to the total amount of the material leaving the vertex
capacity constraints
0 ≤ xij ≤ uij for every edge (i,j) E
Flow value and Maximum Flow Problem
Since no material can be lost or added to by going through intermediate vertices of the network, the total
amount of the material leaving the source must end up at the sink:
∑ x1j = ∑ xjn
j: (1,j) є E j: (j,n) є E
The value of the flow is defined as the total outflow from the source (= the total inflow into the sink).
Maximum-Flow Problem as LP problem
Maximize v = ∑ x1j
j: (1,j) E
subject to
Formally represented by a connected weighted digraph with n vertices numbered from 1 to n with the
following properties:
• contains exactly one vertex with no entering edges, called the source (numbered 1)
• contains exactly one vertex with no leaving edges, called the sink (numbered n)
• has positive integer weight uij on each directed edge (i.j), called the edge capacity,
indicating the upper bound on the amount of the material that can be sent from i to j through
this edge
Definition of flow:
A flow is an assignment of real numbers xij to edges (i,j) of a given network that satisfy the following:
flow-conservation requirements: The total amount of material entering an intermediate vertex
must be equal to the total amount of the material leaving the vertex
capacity constraints
0 ≤ xij ≤ uij for every edge (i,j) E
Flow value and Maximum Flow Problem
Since no material can be lost or added to by going through intermediate vertices of the network, the total
amount of the material leaving the source must end up at the sink:
∑ x1j = ∑ xjn
j: (1,j) є E j: (j,n) є E
The value of the flow is defined as the total outflow from the source (= the total inflow into the sink).
Example:
Shortest-Augmenting-Path Algorithm
Generate augmenting path with the least number of edges by BFS as follows.
Starting at the source, perform BFS traversal by marking new (unlabeled) vertices with two labels:
• first label – indicates the amount of additional flow that can be brought from the source to the
vertex being labeled
second label – indicates the vertex from which the vertex being labeled was reached, with ―+‖ or ―–‖ added
to the second label to indicate whether the vertex was reached via a forward or backward edge
The source is always labeled with ∞,-
All other vertices are labeled as follows:
o If unlabeled vertex j is connected to the front vertex i of the traversal queue by a directed
edge from i to j with positive unused capacity rij = uij –xij (forward edge), vertex j is labeled
with lj,i+, where lj = min{li, rij}
o If unlabeled vertex j is connected to the front vertex i of the traversal queue by a directed
edge from j to i with positive flow xji (backward edge), vertex j is labeled lj,i-, where lj =
min{li, xji}
If the sink ends up being labeled, the current flow can be augmented by the amount indicated by the
sink‘s first label
The augmentation of the current flow is performed along the augmenting path traced by following
CS 6402 -Design And Analysis of Algorithm
the vertex second labels from sink to source; the current flow quantities are increased on the forward
edges and decreased on the backward edges of this path
If the sink remains unlabeled after the traversal queue becomes empty, the algorithm returns the
current flow as maximum and stops
CS 6402 -Design And Analysis of Algorithm
Definition of a Cut:
Let X be a set of vertices in a network that includes its source but does not include its sink, and let X,
the complement of X, be the rest of the vertices including the sink. The cut induced by this partition of
the vertices is the set of all the edges with a tail in X and a head in X.
Capacity of a cut is defined as the sum of capacities of the edges that compose the cut.
We‘ll denote a cut and its capacity by C(X,X) and c(X,X)
Note that if all the edges of a cut were deleted from
the network, there would be no directed path from source to sink
Minimum cut is a cut of the smallest capacity in a given network
CS 6402 -Design And Analysis of Algorithm
\
CS 6402 -Design And Analysis of Algorithm
Time Efficiency
The number of augmenting paths needed by the shortest-augmenting-path algorithm never
exceeds nm/2, where n and m are the number of vertices and edges, respectively
Since the time required to find shortest augmenting path by breadth-first search is in
O(n+m)=O(m) for networks represented by their adjacency lists, the time efficiency of the
shortest-augmenting-path algorithm is in O(nm2) for this representation
More efficient algorithms have been found that can run in close to O(nm) time, but these
algorithms don‘t fall into the iterative-improvement paradigm
A bipartite graph is 2-colorable: the vertices can be colored in two colors so that every edge has its vertices
colored differently
Matching in a Graph
A matching in a graph is a subset of its edges with the property that no two edges share a vertex a
matching in this graph
M = {(4,8), (5,9)}
A maximum (or maximum cardinality) matching is a matching with the largest number of edges
• always exists
• not always unique
Free Vertices and Maximum Matching
• A matching in this graph (M)
For a given matching M, a vertex is called free (or unmatched) if it is not an endpoint of any edge in
M; otherwise, a vertex is said to be matched
• If every vertex is matched, then M is a maximum matching
• If there are unmatched or free vertices, then M may be able to be improved
• We can immediately increase a matching by adding an edge connecting
two free vertices (e.g., (1,6) above)
Augmenting Paths and Augmentation
An augmenting path for a matching M is a path from a free vertex in V to a free vertex in U whose
edges alternate between edges not in M and edges in M
The length of an augmenting path is always odd
Adding to M the odd numbered path edges and deleting from it the even numbered path
edges increases the matching size by 1 (augmentation)
One-edge path between two free vertices is special case of augmenting path
• Matching on the right is maximum (perfect matching)
Step 1 While there are free men, arbitrarily select one of them and do the following:
Proposal The selected free man m proposes to w, the next woman on his preference list
CS 6402 -Design And Analysis of Algorithm
Response If w is free, she accepts the proposal to be matched with m. If she is not free, she
compares m with her current mate. If she prefers m to him, she accepts m‘s proposal, making her former
mate free; otherwise, she simply rejects m‘s proposal, leaving m free
Step 2 Return the set of n matched pairs
men‘s preferences women‘s preferences
st nd rd
1 2 3 1st 2nd 3rd
Bob: Lea Ann Sue Ann: Jim Tom Bob
Jim: Lea Sue Ann Lea: Tom Bob Jim
Tom: Sue Lea Ann Sue: Jim Tom Bob
ranking matrix
Ann Lea Sue
Bob 2,3 1,2 3,3
Jim 3,1 1,3 2,1
Tom 3,2 2,1 1,2
{(Bob, Ann) (Jim, Lea) (Tom, Sue)} is unstable
{(Bob, Ann) (Jim, Sue) (Tom, Lea)} is stable
Free men:
Bob, Jim, Tom
CS 6402 -Design And Analysis of Algorithm
The algorithm terminates after no more than n 2 iterations with a stable marriage output
The stable matching produced by the algorithm is always man-optimal: each man gets the highest
rank woman on his list under any stable marriage. One can obtain the womanoptimal matching by
making women propose to men
A man (woman) optimal matching is unique for a given set of participant preferences
The stable marriage problem has practical applications such as matching medical-school graduates
with hospitals for residency training
CS 6402 -Design And Analysis of Algorithm
UNIT V
8. What is heuristic?
A heuristic is common sense rule drawn from experience rather than from mathematically proved
assertion.
For example, going to the nearest un visited city in the travelling salesman problem is good example
for heuristic.
10. Give the upper bound and lower bound of matrix multiplication algorithm?
Upper bound: The given algorithm does n*n*n multiplication hence at most n*n*n multiplication
are necessary.
Lower bound: It has been proved in the literature that at least n*n multiplication are necessary.
13. What are the additional items are required for branch and bound compare to
backtracking technique?
Compared to backtracking, branch and bound requires 2 additional items.
1) A way to proved , for every node of node of state space tree, a bound on the best value of the
objective function on any solution that can be obtain d by adding further components to the partial
solutionrepresented by the node.
2) The value of the best solution seen so far.
PART B
Example:
This technique is illustrated by the following figure.
Here the algorithm goes from the start node to node 1 and then to node 2.
When no solution is found it backtracks to node1 and goes to the next possible solution node 3. But
node 3 is also a dead-end.
Hence the algorithm backtracks once again to node 1 and then to the start node. From here it goes to
node 4 and repeats the procedure till node 6 is identified as the solution.
CS 6402 -Design And Analysis of Algorithm
Definition: I
An algorithm solves a problem in polynomial time if its worst case time efficiency belongs to O (P (n)).
P (n) is a polynomial of the problem‘s input size n.
Tractable:
Problems that can be solved in polynomial time are called tractable.
Intractable:
Problems that cannot be solved in polynomial time are called intractable. We cannot solve arbitrary
instances in reasonable amount of time.
Huge difference between running time. Sum and composition of 2 polynomial results in polynomial
.Development of extensive theory called computational complexity
Definition: II
P and NP Problems:
Class P
It is a class of decision problems that can be solved in polynomial time by deterministic algorithm,
where as deterministic algorithm is every operation uniquely defined.
Decision problems:
A problem with yes/no answers called decision problem
Restriction of P to decision problems. Sensible to execute problems not solvable in polynomial time
because of their large output. Eg: Subset of the given set
Many important problems that are decision problem can be reduced to a series of decision problems
that are easier to study.
Undecidable problem:
Some decision problems cannot be solved at all by any algorithm.
Halting Problem:
Given a computer program and an input to it, determine whether the program halt at input or continue
work indefinitely on it.
Proof:
Consider A is an Algorithm that solve halting problem.
CS 6402 -Design And Analysis of Algorithm
There are some problems that can be solved in polynomial time(i.e) no polynomial time algorithm.
Some are decision problems that can also be solved.
Eg:
Hamiltonian circuit problem
Travelling salesman problem
Knapsack problem
Partition problem
Bin Packing
Graph coloring
Definition: VI
A decision problem D is said to be NP Complete if it belongs to class NP.Every problem in NP is
ploynomially reducible to p.
E.g.: CNF statisfiability problem
It deals with Boolean expressions. Boolean expression represented in conjunctive normal form.
Consider a expression needs 3 variables x1, x2 and x3 where ~x1, ~x2, ~x3 are negation.
(x1V~x2V~x3) & (~x1Vx2) & (~x1V~x2V~x3)
P≠NP,
Decision problem in NP-Complete:
A decision problem in NP- complete can be done in 2 ways.
1. A string is generated in polynomial time for Non-Polynomial problem. That string says whether it
is possible or not to solve the problem.
2. . Every problem in NP is reducible to a problem in polynomial time
Graph coloring:
A coloring of a graph G=(V,E) is a function f:->{1,2…..k} defined V I € v.If (u.v) € E,then f(u)≠f(v).
The chromatic number decision problem is to determine whether G has a coloring for a given K.
Let G=(V,E) where v={v1,v2,….vn} and the colors be positive integers, the sequential coloring strategy(sc)
always colors the next vertex say vi with minimum acceptable color.
Algorithm:
Input: G= (V, E) an undirected graph where v= {v1, v2…vn}
CS 6402 -Design And Analysis of Algorithm
Output: A coloring of G
Sequential coloring (V, E)
int c,i
for(i=1; i<=n;i++)
for(c=1; c<=n;c++)
if no vertex adjacent to ui has color c
color ui with c
break I //exit for(c)
//continue for(c)
//continue for(i)
for(i=1;i<=5;i++)
for(c=1;c<=5;c++)
i=1, c=1 No vertex adjacent to v1 has color i
Color v1 with color 1
Break
i=2, c=1 v1 is adjacent to v2 having the same color 1
Continue for c
C=2 No vertex adjacent to v2 having the color 2
Color v2 with color 2
Break
i=3, c=1 No vertex adjacent to v3 having the color 1
color v3 with color 1
break
i=4, c=1 v3 is adjacent to v4 having color 1
continue for c
c=2 No vertex adjacent to v3 having the color 2.
Color v4 with color 2
Break
i=5,c=1 No vertex adjacent to v5 having color 1
color u5 with color 1
break
Knapsack problem:
Given n items of known weights w1, w2….wn and values v1, v2...n and a knapsack of weight capacity
w,find the most valuable subset of times that fits in to the knapsack.
This problem can be solved by
Exhaustive search
Dynamic programming
Branch and Bound
Capacity=10
Compute value to weight ratio
Sort items in decreasing order
Approximation Schemes:
CS 6402 -Design And Analysis of Algorithm
Approximation Sa (K)
F (Sa (k))/f(S*) <=1+1/k for any instances of size n
Where k is integer parameter. Range 0<=k<n
Example: K=2
Solution = {1, 3, 4}
It is theoretical than practical
Approximating the optimal solution with any predefined accuracy level.
Time efficiency of this algorithm is polynomial in a.
Total no of subsets the algorithm generates before adding extra element is O (n) time to determine the
subsets possible. Thus algorithm efficiency is O.