Week6 Chap4 Greedy
Week6 Chap4 Greedy
GREEDY ALGORITHMS
1
CONTENT
2
Basis of Greedy algorithms
• Notations Greedy() {
• 𝑺: solution under construction S = ;
• 𝑪: set of candidates while C and not solution(S){
x = select(C);
• 𝒔𝒆𝒍𝒆𝒄𝒕(𝑪): select a potential candidate for inserting to
C = C \ {x};
the solution
if feasible(S {x}) {
• 𝒔𝒐𝒍𝒖𝒕𝒊𝒐𝒏(𝑺): return TRUE if S is a complete accepted S = S {x};
solution, and return FALSE, otherwise }
• 𝒇𝒆𝒂𝒔𝒊𝒃𝒍𝒆(𝑺): return TRUE if 𝑆 does not violate given }
constraints, and return FALSE, otherwise return S;
}
3
Basis of Greedy algorithms
4
Basis of Greedy algorithms
• In general, greedy algorithms cannot ensure to find optimal solutions in all cases
• In some cases, there exist greedy algorithms and can find optimal solutions
• Coin exchange with denominations 1, 2, 5, 10
• Disjoint segments
• Kruskal, Prim algorithms for finding minimum spanning tree of a given undirected weighted graph
• Huffman code
5
Coin exchange problem
6
Knapsack Problem
• There are n items S ={1, 2, 3, . . ., n}. Item j has weight Wj and value Cj (j = 1, 2, . . . n). Given a bin
with capacity B. Select a subset S of items from the given items such that the sum of weights of
items of S is not greater than B and the sum of values of the items is maximal.
7
Knapsack Problem: Greedy 1
8
Knapsack Problem: Greedy 1
• Counter example
• Number of items n = 3
• Capacity of the bin B = 19
Items 1 2 3
Ci 20 16 8
Wi 14 6 10
9
Knapsack Problem: Greedy 2
10
Knapsack Problem: Greedy 2
• Counter example
• Number of items n = 3
• Capacity of the bin B = 11
Items 1 2 3
Cj 10 16 28
Wj 5 6 10
11
Knapsack Problem: Greedy 3
12
Knapsack Problem: Greedy 3
• Counter example
• Number of items n = 2
• Capacity of the bin B ≥ 2
Item 1 2
Ci 10 10B – 1
Wi 1 B
𝐶1 10 10𝐵−1 𝐶2
• Clearly: = ≥ =
𝑊1 1 𝐵 𝑊2
• Solution returned by the Greedy3: S3 = {1} with value 10
• Optimal solution S* = {2} with value 10B - 1
13
Knapsack Problem: Greedy 4
• Let Sj be the solution obtained by Greedyj, (j = 1, 2, 3). Let S4 be the best solution
among S1, S2, S3:
1
• Then we have σ𝑖 𝑆4 𝐶𝑖 ≥ 𝑂𝑃𝑇 (in which OPT is the total values of the optimal
2
solution)
14
Knapsack Problem: Greedy 4
• Counter example
• Number of items n = 4
• Capacity of the bin B = 11
Items 1 2 3 4
Ci 9 10 18 27
Wi 4 5 6 10
Ci/Wi 2.25 2 3 2.7
Greedyi 27 19 27 7
15
Disjoint segments
16
Greedy algorithm ideas
17
Greedy algorithm ideas
• Counter examples
Greedy 1
Greedy 3
Greedy 4
18
Disjoint segments: Greedy 2 is correct
19
THANK YOU !
20