Greedy algorithm
Definition
An algorithm that always takes the best immediate, or local, solution while finding an answer. Greedy algorithms find the overall, or globally, optimal solution for some optimization problems, but may find less-than-optimal solutions for some instances of other problems.
2
อัลกอริทึมเชิงละโมบ
3
ปัญหาต้นไม้ทวิภาค
4
ข้อมูล | ความถี่ |
พู | 25% |
ชินจัง | 22% |
ทิกเกอร์ | 20% |
ดิบซี่ | 18% |
ล้าลา | 8% |
ทิงกี้วิงกี้ | 5% |
โพ | 2% |
ต้นไม้มีต้นทุนที่ = 2.43 ซึ่งไม่ใช่ต่ำสุด
Characteristic of Greedy algorithm
5
ปัญหาถุงเป้ (Knapsack)
6
Knapsack Example: weight ไม่เกิน 10
1)
2)
3)
7
item | weight | value |
1 | 3 | 25 |
2 | 2 | 20 |
3 | 1 | 15 |
4 | 4 | 40 |
5 | 5 | 50 |
Greedy changing-making algorithm
procedure change(c1, c2, … cr: ค่าของเหรียญ, c1 > c2 > … > cr : int){
for(i = 1 to r)
while (n >= ci) {
add a coin with value ci to the change
n = n - ci
}
}
8
Example! where c1 = 20, c2 = 15, c3 = 7, c4 = 1 and we want to give 22 “cents” in change.
Example!, let c1 = 25, c2 = 10, c3 = 5, c4 = 1.
วิธีสั้นสุดแบบแหล่งต้นทางเดียว (shortest path)
9
ต้นไม้แบบทอดข้ามเล็กสุด (Minimum spanning tree)
10
Kruskal algorithm
11
Prim’s algorithm
12
Huffman code
13
Floyd Warshall Algorithm: All-pairs Shortest-paths
14