05. greedy method

15
Kamalesh Karmakar, Assistant Professor, Dept. of C.S.E. Meghnad Saha Institute of Technology

Upload: onkar-nath-sharma

Post on 17-Jul-2015

257 views

Category:

Engineering


1 download

TRANSCRIPT

Page 1: 05. greedy method

Kamalesh Karmakar,Assistant Professor,

Dept. of C.S.E.

Meghnad Saha Institute of Technology

Page 2: 05. greedy method
Page 3: 05. greedy method

Algorithms for optimization problems typically go through asequence of steps, with a set of choices at each step. For manyoptimization problems, using dynamic programming to determinethe best choices is overkill; simpler, more efficient algorithms will do.

A greedy algorithm always makes the choice that looks best at themoment. That is, it makes a locally optimal choice in the hope thatthis choice will lead to a globally optimal solution.

Greedy algorithms do not always yield optimal solutions, but formany problems they do.

Page 4: 05. greedy method
Page 5: 05. greedy method

We are given n objects and a knapsack. Object I has an weight wi andthe knapsack has the capacity m. If a fraction xi, 0<= xi<=1 ofobject i is placed into the knapsack, then a profit of pi xi is earned.

Objective:

maximize ∑ pi xi

1<=i<=n

maximize ∑ wi xi <=m

1<=i<=n

and 0 <= xi <= 1, 1<= I <= n

A feasible solution is any set (x1, x2,….., xn) satisfying all the above

solution.

Page 6: 05. greedy method

AlgorithmGeadyKnapsack (m,n)/* p[1:n] and w[1:n] contain the profit and weights respectively of the

n objects ordered such that p[i]/w[i] >= p[i+1]/w[i+1]. M is the

knapsack size and x[1:n] is the solution vector. */

{

for i:=1 to n do x[i] := 0.0; // Initialize

U := m;

for i :=1 to n do

{

if (w[i] > U) then break;

x[i] := 1.0; U := U –w[i];

}

if (i <= n) then x[i] := U/w[i];

}

Page 7: 05. greedy method

High level description of Job Sequencing Algorithm

Page 8: 05. greedy method

Algorithm JS (d, j, n)/* d[i] >=1, 1<=i<=n are the deadlines, n>=1. The jobs are ordered such thatp[1]>=p[2]>=….>=p[n]. J[i] is the ith job in the optimal solution, 1<=i<=k. Also attermination d[J[i]] <= d[J[i+1]], 1<=i<k*/

{d[0]:=J[0]:=0; // Initialize.J[1]:=1; // Include Job 1.k:=1;for i:=2 to n do{

// Consider jobs in non-increasing order of p[i]. Find position// of I and check feasibility of insertion.r := k;while ((d[J[r]]> d[i]) and (d[J[r]]!=r)) do r := r -1;if ((d[J[r] <= d[i]) and (d[i]>r)) then{

// Insert I into J[]for q := k to (r+1) step -1 do J[q+1] :=J[q];J[r+1] :=i ; k :=k+1;

}}return k;

}

Page 9: 05. greedy method

Prim’sAlgorithm

Kruskal’s Algorithm

Page 10: 05. greedy method
Page 11: 05. greedy method
Page 12: 05. greedy method
Page 13: 05. greedy method
Page 14: 05. greedy method
Page 15: 05. greedy method