DAA R21 Unit2
DAA R21 Unit2
II Sem CSE
UNIT II
The Greedy Method: The general Method, knapsack problem, minimum-cost spanning Trees, Optimal
Merge Patterns, Single Source Shortest Paths.
……………………………………………………………………………………………………………………………..
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.
Components of Greedy Algorithm
Greedy algorithms have the following five components −
A candidate set − A solution is created from this set.
A selection function − Used to choose the best candidate to be added to the solution.
A feasibility function − Used to determine whether a candidate can be used to contribute to the
solution.
An objective function − Used to assign a value to a solution or a partial solution.
A solution function − Used to indicate whether a complete solution has been reached.
Areas of Application
Greedy approach is used to solve many problems, such as
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.
Where Greedy Approach Fails
In many problems, Greedy algorithm fails to find an optimal solution, moreover it may produce a worstsolution.
Problems like Travelling Salesman and Knapsack cannot be solved using this approach.
General method of greedy
Algorithm greedy(a,n)
{
For i=1 to n do
{
X=select(a)
If feasible(x) then
Solution = solution+x;
}
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 1 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
2. knapsack problem
Given a set of items, each with a weight and a value, determine a subset of items to include in a collection sothat the total
weight is less than or equal to a given limit and the total value is as large as possible.
The knapsack problem is in combinatorial optimization problem. It appears as a subproblem in many, more complex
mathematical models of real-world problems. One general approach to difficult problems is to identify the most
restrictive constraint, ignore the others, solve a knapsack problem, and somehow adjust thesolution to satisfy the ignored
constraints.
Applications
In many cases of resource allocation along with some constraint, the problem can be derived in a similar way of
Knapsack problem. Following is a set of example.
Finding the least wasteful way to cut raw materials
portfolio optimization
Cutting stock problems
Problem Scenario
A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items availablein the store
and weight of ith item is wi and its profit is pi. What items should the thief take?
In this context, the items should be selected in such a way that the thief will carry those items for which he will gain
maximum profit. Hence, the objective of the thief is to maximize the profit.
Based on the nature of the items, Knapsack problems are categorized as
Fractional Knapsack
Knapsack
Fractional Knapsack
In this case, items can be broken into smaller pieces, hence the thief can select fractions of items.According to the
problem statement,
There are n items in the store
Weight of ith item wi>0
Profit for ith item pi>0
and
Capacity of the Knapsack is W
In this version of Knapsack problem, items can be broken into smaller pieces. So, the thief may take only a fraction xi of
ith item.
0⩽xi⩽1
The ith item contributes the weight xi.wi to the total weight in the knapsack and profit xi.pi
to the total profit.
Hence, the objective of this algorithm is to
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 2 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
It is clear that an optimal solution must fill the knapsack exactly, otherwise we could add a fraction of one of the
remaining items and increase the overall profit.
Thus, an optimal solution can be obtained by
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 3 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Analysis
If the provided items are already sorted into a decreasing order of piwi, then the while loop takes a time in
O(n); Therefore, the total time including the sort is in O(n logn).Example
Let us consider that the capacity of the knapsack W = 60 and the list of provided items are shown in thefollowing table –
Solution
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 4 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
We found three spanning trees off one complete graph. A complete undirected graph can have maximum n n-
2 number of spanning trees, where n is the number of nodes. In the above addressed example, n is 3, hence 33−2 = 3
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 5 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 6 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Example: Construct the minimum spanning tree (MST) for the given graph using Prim’s Algorithm-
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 7 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Step-1:
Randomly choose any vertex. ( Here vertex 1)
The vertex connecting to the edge having least weight is usually selected.
Step-2: Now we are at node / Vertex 6, It has two adjacent edges, one is already selected, select second one.
Step-3: Now we are at node 5, it has three edges connected, one is already selected, from reaming two select minimum
cost edge (that is having minimum weight) Such that no loops can be formed by adding thatvertex.
Step-4: Now we are at node 4, select the minimum cost edge from the edges connected to this node. Suchthat no loops
can be formed by adding that vertex.
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 8 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Step-5: Now we are at node 3, since the minimum cost edge is already selected, so to reach node 2 we selected the
edge which cost 16. Then the MST is
Step-6: Now we are at node 2, select minimum cost edge from the edges attached to this node. Such that no loops can be
formed by adding that vertex.
Since all the vertices have been included in the MST, so we stop.Now,
Cost of Minimum Spanning Tree
= Sum of all edge weights
= 10 + 25 + 22 + 12 + 16 + 14
= 99 units
Time Complexity: O(V2), If the input graph is represented using an adjacency list, then the time complexity of Prim’s
algorithm can be reduced to O(E log V) with the help of a binary heap. In this implementation, weare always
considering the spanning tree to start from the root of the graph
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 9 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
2. Kruskal’s Algorithm-
Take the edge with the lowest weight and use it to connect the vertices of graph.
If adding an edge creates a cycle, then reject that edge and go for the next least weight edge.Step-03:
Keep adding edges until all the vertices are connected and a Minimum Spanning Tree (MST) is obtained.
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 10 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Analysis: Where E is the number of edges in the graph and V is the number of vertices, Kruskal's Algorithm can be
shown to run in O (E log E) time, or simply, O (E log V) time, all with simple data structures. These running times are
equivalent because:
E is at most V2 and log V2= 2 x log V is O (log V).
If we ignore isolated vertices, which will each their components of the minimum spanning tree, V ≤
2 E, so log V is O (log E).
Thus, the total time is
1. O (E log E) = O (E log V).
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 11 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Method 2:
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 12 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Method 3:
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 13 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Approach:
Node represents a file with a given size also given nodes are greater than 2
1. Add all the nodes in a priority queue (Min Heap).{pq.poll = file size}
1. int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and
pop(remove) it out
2. weight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it out
3. count +=weight;
Letter zkm c u d l e
Frequency 2 7 24 32 37 42 42 120
Huffman code
e 120 0 1
d 42 101 3
l 42 110 3
u 37 100 3
c 32 1110 4
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 14 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
m 24 11111 5
k 7 111101 6
z 2 111100 6
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 15 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Djikstra used this property in the opposite direction i.e we overestimate the distance of each vertex from thestarting
vertex. Then we visit each node and its neighbors to find the shortest subpath to those neighbors.
The algorithm uses a greedy approach in the sense that we find the next best solution hoping that the endresult is the best
solution for the whole problem.
Example of Dijkstra's algorithm
It is easier to start with an example and then think about the algorithm.
Choose a starting vertex and assign infinity path values to all other devices
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 16 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
If the path length of the adjacent vertex is lesser than new path length, don't update it
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 17 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
After each iteration, we pick the unvisited vertex with the least path length. So we choose 5 before 7
Notice how the rightmost vertex has its path length updated twice
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 18 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 19 of 20
Design & Analysis of Algorithms R21, Autonomous II B. Tech. II Sem CSE
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 20 of 20