SlideShare a Scribd company logo
The Greedy method
The general Method
 The greedy method is a most straight
forward design technique
 Most of these problems have n inputs and
require us to obtain a subset that satisfies
some constraints
 Any subset that satisfies the constraint is
called a feasible solution
 We need to find a feasible solution that
either maximizes or minimizes the given
objective function
 The Greedy method suggest an algorithm
that works in stages, considering one
input at a time
 At each stage a decision is made
regarding whether the particular input is
in an optimal solution
 This is done by selecting the input in a
particular order determined by some
selection procedure
 If the insertion of the next input into
partially constructed optimal solution will
result in an infeasible solution, then this
input is not added to the feasible solution.
Otherwise, it is added
 Algorithm Greedy(a,n)
{
solution:=¢;
For i:=1 to n do
{
X:= select(a);
If feasible(solution,x) then
Solution:=union(solution,x);
}
Return solution
}
 The function select selects an input from
a[] and removes it .the selected input's
value is assigned to x. Feasible is a
Boolean valued function that determines
whether x can be included in to the
solution vector. The function union
combines x with the solution and updates
the objective function
Knapsack Problem
We are given n objects and a knapsack or a bag. Object i has a weight wi, and the
knapsack has a capacity m. If a fraction xi, 0<xi<1, of objects i is placed into the
knapsack, then a profit of pixi is earned.
The objective is to obtain a filling of the knapsack that maximizes the
total profit earned. Since the knapsack capacity is m, we require the total
weight of all chosen objects to be at most m. Formally the problem can
be stated as
The profits and weights are positive numbers.
A feasible solution (or filling) is any set (x1, x2,……,xn) satisfying
II and III above. An optimal solution is a feasible solution for which I is
maximized.
Example: -
Exercise
1. Find an optimal solution to the knapsack instance n =4,
m=40,(p1,p2,p3,p4) = (20,40,35,45) and (w1,w2,w3,w4) = (20,25,10,15).
Strategy 1: consider the object in increasing order of weights
(w3,w4,w1,w2)
Remaining
capacity
object weight Fraction xi
included
40-10=30 3 10 1
30-15=15 4 15 1
15-15=0 1 20 15/20=3/4
Solution vector(x1,x2,x3,x4)=(3/4,0,1,1)
Profit=∑pixi=20*3/4+40*0+35*1+45*1=95
Strategy 2: consider the object in decreasing order of profit
(p4,p2,p3,p1)=(45,40,35,20)
Remaining
capacity
object weight Fraction xi
included
40-15=25 4 15 1
25-25=0 2 25 1
Solution vector(x1,x2,x3,x4)=(0,1,0,1)
Profit=∑pixi=20*0+40*1+35*0+45*1=85
Strategy 3: consider the object in decreasing order of profit/weight(pi/wi)
(P3/w3)>(p4/w4)>(p2/w2)>(p1/w1)
Remaining
capacity
object weight Fraction xi
included
40-10=30 3 10 1
30-15=15 4 15 1
15-15=0 2 25 15/25=3/5
Solution vector(x1,x2,x3,x4)=(0,3/4,1,1)
Profit=∑pixi=20*0+40*3/4+35*1+45*1=104
0/1 Knapsack problem
 In this method item cannot be broken which means object should be taken as a
whole or not taken. Hence it is called 0/1 knapsack Problem.
 Each item is taken or not taken.
 Cannot take a fractional amount of an item taken or take an item more than once.
 Greedy Approach doesn't ensure an Optimal Solution.
 Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other
constraints remain the same.
 Find an optimal solution to the knapsack instance n =4, m=40,(p1,p2,p3,p4) =
(20,40,35,45) and (w1,w2,w3,w4) = (20,25,10,15).
 Strategy 1: consider the object in increasing order of weights (w3,w4,w1,w2)
 Solution vector(x1,x2,x3,x4)=(0,0,1,1)
 Profit=∑pixi=20*0+40*0+35*1+45*1=80
 Even it the capacity of knapsack is not full, we do not consider the next object
i.e)object 1 .
Remaining
capacity
object weight Fraction of
xi
considered
40-10=30 3 10 1
30-15=15 4 15 1
 Strategy 2: consider the object in decreasing order of profits (p4,p3,p2,p1)
 Even it the capacity of knapsack is not full, we do not consider the next
object i.e)object 3 .
 Solution vector(x1,x2,x3,x4)=(0,1,0,1)
Profit=∑pixi=20*0+40*1+35*0+45*1=85
Remaining
capacity
object weight Fraction of
xi
considered
40-15=25 4 15 1
25-25=0 2 25 1
 Strategy 3: consider the object in decreasing order of profits/weights
(p3/w3,p4/w4,p2/w2,p1/w1)
 Even it the capacity of knapsack is not full, we do not consider the
next object i.e)object 2 .
 Solution vector(x1,x2,x3,x4)=(0,0,1,1)
Profit=∑pixi=20*0+40*0+35*1+45*1=80
Remaining
capacity
object weight Fraction of
xi
considered
40-10=30 3 10 1
30-15=15 4 15 1
MST – Minimum Spanning Tree
 Given a connected undirected graph we would like to
find the “cheapest” connected version of that graph
 Remove all extra edges leaving just enough to be
connected – it will be a tree
 A subgraph T=(V,E’)of G=(V,E) is a spanning tree if T is
a tree, and includes all vertices of G and subset of
edges(E’)
 Find the tree that has the smallest sum of edge lengths
 Given G = (V, E) and edge weights we, find the tree T =
(V, E') where E' ⊆ E and which also minimizes
is called Minimum Spanning Tree
 Not necessarily unique
 Many applications – cheapest phone network, etc.
CS 312 – Greedy Algorithms 17
we
eÎE'
å
Prims algorithm
 Prims algorithm constructs a minimum spanning tree
through sequence of expanding sub trees.
 It starts by selecting some arbitrary vertex V of graph of
vertices.
 On each iteration tree expands I greedy manner by
attaching nearest node not in the tree.
 Cost adjacency matrix gives the distance of present
vertex with all other vertices in the graph.
 If the vertex is not reachable from current vertex the
distance is given as ∞
Prims algorithm
 //Assume that G is connected and weighted graph
 //Input: The cost adjacency matrix C and number of vertices n
 //Output: Minimum weight spanning tree T
Algorithm prims(c,n)
{
for i=1 to n do
visited[i]=0
u=1
Visited[u]=1
while there is still unchosen vertices do
{
let(u,v)be the lightest edge between any chosen u and v
Visited[v]=1
T’=union(T,<u,v>)
}
Return T
}
KRUSKAL'S ALGORITHM
KRUSKAL'S ALGORITHM
This algorithm is used for finding the minimum cost
spanning tree for every connected undirected graph.
In the algorithm,
-> E is the set of edges in graph G
-> G has 'n' vertices
-> cost[u,v] is the cost of edge(u,v)
-> ‘T' is the set of edges in the minimum cost spanning
tree
Step1:Arrange the edges in increasing order of
weights
Step 2: Consider all vertices as independent
component
Step 3:Consider the edge if they belong to
different components and does not form a cycle,
reject otherwise.
Step 4: Repeat step 3 until single component
containing all vertices are included.
Algorithm Kruskal(E,n)
{
//Let E is the list of edges
//n is number of vertices in given graph G
Sort E in increasing order of their edge weights;
Initially T=0
While ( T does not contain n-1 edges)do
{
find minimum cost edge not yet considered in E and call it as
(u,v)
If(u,v)Does not form a cycle
T=T+(u,v)
else
delete(u,v)
}
return T
}
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
{1}{2}{3}{4}{5}{6}{7
}
Make a disjoint set for each vertex
24
Kruskal’s Algorithm
Sort edges by weight
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1}{2}{3}{4}{5}{6}{7
}
25
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1}{2}{3}{4}{5}{6}{7
}
Add first edge to X if no cycle created
26
CS 312 – Greedy Algorithms
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
Merge vertices in added edges
27
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
Process each edge in order
{1,2,3}{4}{5}{6}{7}
28
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
{1,2,3}{4}{5}{6}{7}
{1,2,3}{4,5}{6}{7}
Note that each set is a connected component of G
29
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
{1,2,3}{4}{5}{6}{7}
{1,2,3}{4,5}{6}{7}
{1,2,3}{4,5}{6,7}
30
CS 312 – Greedy Algorithms
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
{1,2,3}{4}{5}{6}{7}
{1,2,3}{4,5}{6}{7}
{1,2,3}{4,5}{6,7}
{1,2,3,4,5}{6,7}
31
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
Must join separate components
{1,2,3}{4}{5}{6}{7}
{1,2,3}{4,5}{6}{7}
{1,2,3}{4,5}{6,7}
{1,2,3,4,5}{6,7}
rejected
32
Kruskal’s Algorithm
1 2 3
1 2
4 5 6
3 8
7
4
6
4
5
6
7
3
4
1: {1,2}
2: {2,3}
3: {4,5}
3: {6,7}
4: {1,4}
4: {2,5}
4: {4,7}
5: {3,5}
{1,2}{3}{4}{5}{6}{7}
Done when all vertices in one set
Then they are all connected
Exactly |V| - 1 edges
{1,2,3}{4}{5}{6}{7}
{1,2,3}{4,5}{6}{7}
{1,2,3}{4,5}{6,7}
{1,2,3,4,5}{6,7}
rejected
{1,2,3,4,5,6,7} done
33
Dijikstra’s Algorithm-Single
source shortest path
 Algorithm finds shortest path from given vertex to all
other vertices in a digraph.
 The length of the path is sum of cost of the edges on
the path
 The algorithm finds shortest path from source ‘S’ to all
other vertices, to which there is a path.
 It first finds shortest path to nearest vertex ,then to
second nearest using intermediate nodes and so on.
 Before ith iteration algorithm finds shortest paths to (i-
1)vertices nearest to source.
//v=set of vertices
//c=cost adjacency matrix of digraph G(V,E)
//n=number of vertices in given graph
//D[i]=contains current shortest path to vertex I
//c[i][j] is the cost of going from vertex I to j.If there is no path, assume
//c[i][j]= ∞ and c[i][j]=0
Algorithm Dijikstra(V,C,D,n)
{
s={1}
for i=2 to n do
d[i]=C[1,i]
for i=1 to n do
{
choose a vertex W in V-S such that D[W] is minimum
S=S U W //add W to S
for each vertex V in V-S d
D[V]=min(D[v],D[W],C[W[V])
}
}
Single-Source Shortest Path Problem
Single-Source Shortest Path Problem - The
problem of finding shortest paths from a source
vertex v to all other vertices in the graph.
Applications
- Maps (Map Quest, Google Maps)
- Routing Systems
Dijkstra's algorithm
Dijkstra's algorithm - is a solution to the single-source
shortest path problem in graph theory.
Works on both directed and undirected graphs. However,
all edges must have nonnegative weights.
Input: Weighted graph G={E,V} and source vertex v∈V,
such that all edge weights are nonnegative
Output: Lengths of shortest paths (or the shortest paths
themselves) from a given source vertex v∈V to all other
vertices
Approach
 The algorithm computes for each vertex v the distance
to v from the start vertex S, that is, the weight of a
shortest path between S and v.
 The algorithm keeps track of the set of vertices for
which the distance has been computed, called w
 Every vertex has a label D associated with it. For any
vertex v, D[v] stores an approximation of the distance
between v and w. The algorithm will update a D[v] value
when it finds a shorter path from w to v.
 When a vertex w is added to S, its label D[v] is equal to
the actual (final) distance between the starting vertex S
and vertex v.
39
40
Example: Initialization
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0
Pick vertex in List with minimum distance.
Distance(source) =0
S={A}
Find the nearest
vertex to source say w
i.e)D
V={A,B,C,D.E,F,G}
41
Example: Update neighbors'
distance
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
Distance(B) = 2
Distance(D) = 1
42
Example: consider vertex with
minimum distance
Pick vertex in List with minimum distance, i.e., D
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0
1
43
Example: Update neighbors
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
9 5
Distance(C) = 1 + 2 = 3
Distance(E) = 1 + 2 = 3
Distance(F) = 1 + 8 = 9
Distance(G) = 1 + 4 = 5
Use D as intermediate
44
Example: Continued...
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
Pick vertex in List with minimum distance (B) and update neighbors
9 5
Note : distance(D) not
updated since D is
already known and
distance(E) not updated
since it is larger than
previously computed
45
Example: Continued...
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
9 5
No updating
Pick vertex List with minimum distance (E) and update neighbors
46
Example: Continued...
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
8 5
Pick vertex List with minimum distance (C) and update neighbors
Distance(F) = 3 + 5 = 8
47
Example: Continued...
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
6 5
Distance(F) = min (8, 5+1) = 6
Previous distance
Pick vertex List with minimum distance (G) and update neighbors
48
Example (end)
A
G
F
B
E
C D
4 1
2
10
3
6
4
2
2
8
5
1
0 2
3 3
1
Pick vertex not in S with lowest cost (F) and update neighbors
6 5
Job sequencing with Deadline
 Job J1 J2 J3 J4 J5
 Deadline 2 1 3 2 1
 Profit 60 100 20 40 20
 Solution
 To solve this problem, the given jobs are sorted
according to their profit in a descending order.
Hence, after sorting, the jobs are ordered as
shown in the following table.
 Job J2 J1 J4 J3 J5
 Deadline 1 2 2 3 1
 Profit 100 60 40 20 20
 From this set of jobs, first we select J2, as it can be completed
within its deadline and contributes maximum profit.
 Next, J1 is selected as it gives more profit compared to J4.
 In the next clock, J4 cannot be selected as its deadline is over,
hence J3 is selected as it executes within its deadline.
 The job J5 is discarded as it cannot be executed within its deadline.
 Thus, the solution is the sequence of jobs (J2, J1, J3), which are
being executed within their deadline and gives maximum profit.

More Related Content

What's hot

Data Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and ConquerData Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and Conquer
Laguna State Polytechnic University
 
Bellman Ford's Algorithm
Bellman Ford's AlgorithmBellman Ford's Algorithm
Bellman Ford's Algorithm
Tanmay Baranwal
 
Branch and bound.ppt
Branch and bound.pptBranch and bound.ppt
Branch and bound.ppt
umairshams6
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
Sujata Pardeshi
 
Convex hull
Convex hullConvex hull
Convex hull
Shiwangi Thakur
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
Madhu Bala
 
Perceptron 2015.ppt
Perceptron 2015.pptPerceptron 2015.ppt
Perceptron 2015.ppt
SadafAyesha9
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
Dr Shashikant Athawale
 
Push down automata
Push down automataPush down automata
Push down automata
Somya Bagai
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
HoneyChintal
 
Perceptron & Neural Networks
Perceptron & Neural NetworksPerceptron & Neural Networks
Perceptron & Neural Networks
NAGUR SHAREEF SHAIK
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
Jyotsna Suryadevara
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
Np complete
Np completeNp complete
03 Single layer Perception Classifier
03 Single layer Perception Classifier03 Single layer Perception Classifier
03 Single layer Perception Classifier
Tamer Ahmed Farrag, PhD
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
Dr. C.V. Suresh Babu
 
Depth Buffer Method
Depth Buffer MethodDepth Buffer Method
Depth Buffer Method
Ummiya Mohammedi
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
Vipul Chauhan
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysis
ajmalcs
 

What's hot (20)

Data Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and ConquerData Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and Conquer
 
Bellman Ford's Algorithm
Bellman Ford's AlgorithmBellman Ford's Algorithm
Bellman Ford's Algorithm
 
Branch and bound.ppt
Branch and bound.pptBranch and bound.ppt
Branch and bound.ppt
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
 
Convex hull
Convex hullConvex hull
Convex hull
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
 
Perceptron 2015.ppt
Perceptron 2015.pptPerceptron 2015.ppt
Perceptron 2015.ppt
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Push down automata
Push down automataPush down automata
Push down automata
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
 
Perceptron & Neural Networks
Perceptron & Neural NetworksPerceptron & Neural Networks
Perceptron & Neural Networks
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
Np complete
Np completeNp complete
Np complete
 
03 Single layer Perception Classifier
03 Single layer Perception Classifier03 Single layer Perception Classifier
03 Single layer Perception Classifier
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
 
Depth Buffer Method
Depth Buffer MethodDepth Buffer Method
Depth Buffer Method
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysis
 

Similar to Unit 3-Greedy Method

Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
MaryJacob24
 
Data structure notes
Data structure notesData structure notes
Data structure notes
anujab5
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
MaryJacob24
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
MaryJacob24
 
final-ppts-daa-unit-iii-greedy-method.pdf
final-ppts-daa-unit-iii-greedy-method.pdffinal-ppts-daa-unit-iii-greedy-method.pdf
final-ppts-daa-unit-iii-greedy-method.pdf
JasmineSayyed3
 
module4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdfmodule4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdf
Shiwani Gupta
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
hodcsencet
 
UNIT-II.pptx
UNIT-II.pptxUNIT-II.pptx
UNIT-II.pptx
JyoReddy9
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhhCh3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
danielgetachew0922
 
Unit-2 Branch & Bound Design of Algorithms.ppt
Unit-2 Branch & Bound Design of Algorithms.pptUnit-2 Branch & Bound Design of Algorithms.ppt
Unit-2 Branch & Bound Design of Algorithms.ppt
HarjotDhillon8
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
SHC
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 
Daa chapter11
Daa chapter11Daa chapter11
Daa chapter11
B.Kirron Reddi
 
IRJET- Solving Quadratic Equations using C++ Application Program
IRJET-  	  Solving Quadratic Equations using C++ Application ProgramIRJET-  	  Solving Quadratic Equations using C++ Application Program
IRJET- Solving Quadratic Equations using C++ Application Program
IRJET Journal
 
Lecture#9
Lecture#9Lecture#9
Lecture#9
Ali Shah
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
yashodamb
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt
RohitPaul71
 
test pre
test pretest pre
test pre
farazch
 

Similar to Unit 3-Greedy Method (20)

Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
 
Data structure notes
Data structure notesData structure notes
Data structure notes
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
 
final-ppts-daa-unit-iii-greedy-method.pdf
final-ppts-daa-unit-iii-greedy-method.pdffinal-ppts-daa-unit-iii-greedy-method.pdf
final-ppts-daa-unit-iii-greedy-method.pdf
 
module4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdfmodule4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
UNIT-II.pptx
UNIT-II.pptxUNIT-II.pptx
UNIT-II.pptx
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhhCh3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
 
Unit-2 Branch & Bound Design of Algorithms.ppt
Unit-2 Branch & Bound Design of Algorithms.pptUnit-2 Branch & Bound Design of Algorithms.ppt
Unit-2 Branch & Bound Design of Algorithms.ppt
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Daa chapter11
Daa chapter11Daa chapter11
Daa chapter11
 
IRJET- Solving Quadratic Equations using C++ Application Program
IRJET-  	  Solving Quadratic Equations using C++ Application ProgramIRJET-  	  Solving Quadratic Equations using C++ Application Program
IRJET- Solving Quadratic Equations using C++ Application Program
 
Lecture#9
Lecture#9Lecture#9
Lecture#9
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt
 
test pre
test pretest pre
test pre
 

More from DevaKumari Vijay

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
DevaKumari Vijay
 
Os ch1
Os ch1Os ch1
Unit2
Unit2Unit2
Unit 1
Unit 1Unit 1
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
DevaKumari Vijay
 
Decisiontree&amp;game theory
Decisiontree&amp;game theoryDecisiontree&amp;game theory
Decisiontree&amp;game theory
DevaKumari Vijay
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
DevaKumari Vijay
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
DevaKumari Vijay
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
DevaKumari Vijay
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
DevaKumari Vijay
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
DevaKumari Vijay
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
DevaKumari Vijay
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
DevaKumari Vijay
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
DevaKumari Vijay
 

More from DevaKumari Vijay (20)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
 
Os ch1
Os ch1Os ch1
Os ch1
 
Unit2
Unit2Unit2
Unit2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
 
Decisiontree&amp;game theory
Decisiontree&amp;game theoryDecisiontree&amp;game theory
Decisiontree&amp;game theory
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 

Recently uploaded

The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 

Unit 3-Greedy Method

  • 2. The general Method  The greedy method is a most straight forward design technique  Most of these problems have n inputs and require us to obtain a subset that satisfies some constraints  Any subset that satisfies the constraint is called a feasible solution
  • 3.  We need to find a feasible solution that either maximizes or minimizes the given objective function  The Greedy method suggest an algorithm that works in stages, considering one input at a time  At each stage a decision is made regarding whether the particular input is in an optimal solution
  • 4.  This is done by selecting the input in a particular order determined by some selection procedure  If the insertion of the next input into partially constructed optimal solution will result in an infeasible solution, then this input is not added to the feasible solution. Otherwise, it is added
  • 5.  Algorithm Greedy(a,n) { solution:=¢; For i:=1 to n do { X:= select(a); If feasible(solution,x) then Solution:=union(solution,x); } Return solution }
  • 6.  The function select selects an input from a[] and removes it .the selected input's value is assigned to x. Feasible is a Boolean valued function that determines whether x can be included in to the solution vector. The function union combines x with the solution and updates the objective function
  • 7. Knapsack Problem We are given n objects and a knapsack or a bag. Object i has a weight wi, and the knapsack has a capacity m. If a fraction xi, 0<xi<1, of objects i is placed into the knapsack, then a profit of pixi is earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned. Since the knapsack capacity is m, we require the total weight of all chosen objects to be at most m. Formally the problem can be stated as The profits and weights are positive numbers. A feasible solution (or filling) is any set (x1, x2,……,xn) satisfying II and III above. An optimal solution is a feasible solution for which I is maximized.
  • 9.
  • 10. Exercise 1. Find an optimal solution to the knapsack instance n =4, m=40,(p1,p2,p3,p4) = (20,40,35,45) and (w1,w2,w3,w4) = (20,25,10,15). Strategy 1: consider the object in increasing order of weights (w3,w4,w1,w2) Remaining capacity object weight Fraction xi included 40-10=30 3 10 1 30-15=15 4 15 1 15-15=0 1 20 15/20=3/4 Solution vector(x1,x2,x3,x4)=(3/4,0,1,1) Profit=∑pixi=20*3/4+40*0+35*1+45*1=95
  • 11. Strategy 2: consider the object in decreasing order of profit (p4,p2,p3,p1)=(45,40,35,20) Remaining capacity object weight Fraction xi included 40-15=25 4 15 1 25-25=0 2 25 1 Solution vector(x1,x2,x3,x4)=(0,1,0,1) Profit=∑pixi=20*0+40*1+35*0+45*1=85
  • 12. Strategy 3: consider the object in decreasing order of profit/weight(pi/wi) (P3/w3)>(p4/w4)>(p2/w2)>(p1/w1) Remaining capacity object weight Fraction xi included 40-10=30 3 10 1 30-15=15 4 15 1 15-15=0 2 25 15/25=3/5 Solution vector(x1,x2,x3,x4)=(0,3/4,1,1) Profit=∑pixi=20*0+40*3/4+35*1+45*1=104
  • 13. 0/1 Knapsack problem  In this method item cannot be broken which means object should be taken as a whole or not taken. Hence it is called 0/1 knapsack Problem.  Each item is taken or not taken.  Cannot take a fractional amount of an item taken or take an item more than once.  Greedy Approach doesn't ensure an Optimal Solution.  Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other constraints remain the same.
  • 14.  Find an optimal solution to the knapsack instance n =4, m=40,(p1,p2,p3,p4) = (20,40,35,45) and (w1,w2,w3,w4) = (20,25,10,15).  Strategy 1: consider the object in increasing order of weights (w3,w4,w1,w2)  Solution vector(x1,x2,x3,x4)=(0,0,1,1)  Profit=∑pixi=20*0+40*0+35*1+45*1=80  Even it the capacity of knapsack is not full, we do not consider the next object i.e)object 1 . Remaining capacity object weight Fraction of xi considered 40-10=30 3 10 1 30-15=15 4 15 1
  • 15.  Strategy 2: consider the object in decreasing order of profits (p4,p3,p2,p1)  Even it the capacity of knapsack is not full, we do not consider the next object i.e)object 3 .  Solution vector(x1,x2,x3,x4)=(0,1,0,1) Profit=∑pixi=20*0+40*1+35*0+45*1=85 Remaining capacity object weight Fraction of xi considered 40-15=25 4 15 1 25-25=0 2 25 1
  • 16.  Strategy 3: consider the object in decreasing order of profits/weights (p3/w3,p4/w4,p2/w2,p1/w1)  Even it the capacity of knapsack is not full, we do not consider the next object i.e)object 2 .  Solution vector(x1,x2,x3,x4)=(0,0,1,1) Profit=∑pixi=20*0+40*0+35*1+45*1=80 Remaining capacity object weight Fraction of xi considered 40-10=30 3 10 1 30-15=15 4 15 1
  • 17. MST – Minimum Spanning Tree  Given a connected undirected graph we would like to find the “cheapest” connected version of that graph  Remove all extra edges leaving just enough to be connected – it will be a tree  A subgraph T=(V,E’)of G=(V,E) is a spanning tree if T is a tree, and includes all vertices of G and subset of edges(E’)  Find the tree that has the smallest sum of edge lengths  Given G = (V, E) and edge weights we, find the tree T = (V, E') where E' ⊆ E and which also minimizes is called Minimum Spanning Tree  Not necessarily unique  Many applications – cheapest phone network, etc. CS 312 – Greedy Algorithms 17 we eÎE' å
  • 18. Prims algorithm  Prims algorithm constructs a minimum spanning tree through sequence of expanding sub trees.  It starts by selecting some arbitrary vertex V of graph of vertices.  On each iteration tree expands I greedy manner by attaching nearest node not in the tree.  Cost adjacency matrix gives the distance of present vertex with all other vertices in the graph.  If the vertex is not reachable from current vertex the distance is given as ∞
  • 19. Prims algorithm  //Assume that G is connected and weighted graph  //Input: The cost adjacency matrix C and number of vertices n  //Output: Minimum weight spanning tree T Algorithm prims(c,n) { for i=1 to n do visited[i]=0 u=1 Visited[u]=1 while there is still unchosen vertices do { let(u,v)be the lightest edge between any chosen u and v Visited[v]=1 T’=union(T,<u,v>) } Return T }
  • 21. KRUSKAL'S ALGORITHM This algorithm is used for finding the minimum cost spanning tree for every connected undirected graph. In the algorithm, -> E is the set of edges in graph G -> G has 'n' vertices -> cost[u,v] is the cost of edge(u,v) -> ‘T' is the set of edges in the minimum cost spanning tree
  • 22. Step1:Arrange the edges in increasing order of weights Step 2: Consider all vertices as independent component Step 3:Consider the edge if they belong to different components and does not form a cycle, reject otherwise. Step 4: Repeat step 3 until single component containing all vertices are included.
  • 23. Algorithm Kruskal(E,n) { //Let E is the list of edges //n is number of vertices in given graph G Sort E in increasing order of their edge weights; Initially T=0 While ( T does not contain n-1 edges)do { find minimum cost edge not yet considered in E and call it as (u,v) If(u,v)Does not form a cycle T=T+(u,v) else delete(u,v) } return T }
  • 24. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 {1}{2}{3}{4}{5}{6}{7 } Make a disjoint set for each vertex 24
  • 25. Kruskal’s Algorithm Sort edges by weight 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1}{2}{3}{4}{5}{6}{7 } 25
  • 26. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1}{2}{3}{4}{5}{6}{7 } Add first edge to X if no cycle created 26 CS 312 – Greedy Algorithms
  • 27. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} Merge vertices in added edges 27
  • 28. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} Process each edge in order {1,2,3}{4}{5}{6}{7} 28
  • 29. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} {1,2,3}{4}{5}{6}{7} {1,2,3}{4,5}{6}{7} Note that each set is a connected component of G 29
  • 30. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} {1,2,3}{4}{5}{6}{7} {1,2,3}{4,5}{6}{7} {1,2,3}{4,5}{6,7} 30 CS 312 – Greedy Algorithms
  • 31. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} {1,2,3}{4}{5}{6}{7} {1,2,3}{4,5}{6}{7} {1,2,3}{4,5}{6,7} {1,2,3,4,5}{6,7} 31
  • 32. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} Must join separate components {1,2,3}{4}{5}{6}{7} {1,2,3}{4,5}{6}{7} {1,2,3}{4,5}{6,7} {1,2,3,4,5}{6,7} rejected 32
  • 33. Kruskal’s Algorithm 1 2 3 1 2 4 5 6 3 8 7 4 6 4 5 6 7 3 4 1: {1,2} 2: {2,3} 3: {4,5} 3: {6,7} 4: {1,4} 4: {2,5} 4: {4,7} 5: {3,5} {1,2}{3}{4}{5}{6}{7} Done when all vertices in one set Then they are all connected Exactly |V| - 1 edges {1,2,3}{4}{5}{6}{7} {1,2,3}{4,5}{6}{7} {1,2,3}{4,5}{6,7} {1,2,3,4,5}{6,7} rejected {1,2,3,4,5,6,7} done 33
  • 34. Dijikstra’s Algorithm-Single source shortest path  Algorithm finds shortest path from given vertex to all other vertices in a digraph.  The length of the path is sum of cost of the edges on the path  The algorithm finds shortest path from source ‘S’ to all other vertices, to which there is a path.  It first finds shortest path to nearest vertex ,then to second nearest using intermediate nodes and so on.  Before ith iteration algorithm finds shortest paths to (i- 1)vertices nearest to source.
  • 35. //v=set of vertices //c=cost adjacency matrix of digraph G(V,E) //n=number of vertices in given graph //D[i]=contains current shortest path to vertex I //c[i][j] is the cost of going from vertex I to j.If there is no path, assume //c[i][j]= ∞ and c[i][j]=0 Algorithm Dijikstra(V,C,D,n) { s={1} for i=2 to n do d[i]=C[1,i] for i=1 to n do { choose a vertex W in V-S such that D[W] is minimum S=S U W //add W to S for each vertex V in V-S d D[V]=min(D[v],D[W],C[W[V]) } }
  • 36. Single-Source Shortest Path Problem Single-Source Shortest Path Problem - The problem of finding shortest paths from a source vertex v to all other vertices in the graph.
  • 37. Applications - Maps (Map Quest, Google Maps) - Routing Systems
  • 38. Dijkstra's algorithm Dijkstra's algorithm - is a solution to the single-source shortest path problem in graph theory. Works on both directed and undirected graphs. However, all edges must have nonnegative weights. Input: Weighted graph G={E,V} and source vertex v∈V, such that all edge weights are nonnegative Output: Lengths of shortest paths (or the shortest paths themselves) from a given source vertex v∈V to all other vertices
  • 39. Approach  The algorithm computes for each vertex v the distance to v from the start vertex S, that is, the weight of a shortest path between S and v.  The algorithm keeps track of the set of vertices for which the distance has been computed, called w  Every vertex has a label D associated with it. For any vertex v, D[v] stores an approximation of the distance between v and w. The algorithm will update a D[v] value when it finds a shorter path from w to v.  When a vertex w is added to S, its label D[v] is equal to the actual (final) distance between the starting vertex S and vertex v. 39
  • 40. 40 Example: Initialization A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 Pick vertex in List with minimum distance. Distance(source) =0 S={A} Find the nearest vertex to source say w i.e)D V={A,B,C,D.E,F,G}
  • 41. 41 Example: Update neighbors' distance A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 Distance(B) = 2 Distance(D) = 1
  • 42. 42 Example: consider vertex with minimum distance Pick vertex in List with minimum distance, i.e., D A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 1
  • 43. 43 Example: Update neighbors A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 9 5 Distance(C) = 1 + 2 = 3 Distance(E) = 1 + 2 = 3 Distance(F) = 1 + 8 = 9 Distance(G) = 1 + 4 = 5 Use D as intermediate
  • 44. 44 Example: Continued... A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 Pick vertex in List with minimum distance (B) and update neighbors 9 5 Note : distance(D) not updated since D is already known and distance(E) not updated since it is larger than previously computed
  • 45. 45 Example: Continued... A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 9 5 No updating Pick vertex List with minimum distance (E) and update neighbors
  • 46. 46 Example: Continued... A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 8 5 Pick vertex List with minimum distance (C) and update neighbors Distance(F) = 3 + 5 = 8
  • 47. 47 Example: Continued... A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 6 5 Distance(F) = min (8, 5+1) = 6 Previous distance Pick vertex List with minimum distance (G) and update neighbors
  • 48. 48 Example (end) A G F B E C D 4 1 2 10 3 6 4 2 2 8 5 1 0 2 3 3 1 Pick vertex not in S with lowest cost (F) and update neighbors 6 5
  • 49. Job sequencing with Deadline  Job J1 J2 J3 J4 J5  Deadline 2 1 3 2 1  Profit 60 100 20 40 20  Solution  To solve this problem, the given jobs are sorted according to their profit in a descending order. Hence, after sorting, the jobs are ordered as shown in the following table.
  • 50.  Job J2 J1 J4 J3 J5  Deadline 1 2 2 3 1  Profit 100 60 40 20 20  From this set of jobs, first we select J2, as it can be completed within its deadline and contributes maximum profit.  Next, J1 is selected as it gives more profit compared to J4.  In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as it executes within its deadline.  The job J5 is discarded as it cannot be executed within its deadline.  Thus, the solution is the sequence of jobs (J2, J1, J3), which are being executed within their deadline and gives maximum profit.