Kru Skal
Kru Skal
• Section 9.2
The Minimum Spanning Tree
•E’ E
•G’ is connected
•G’ has the minimum cost
Example
12 Which is the
A E
MST?
20 Why MST is
20 a tree?
B 6 D
13 C
12
A E
12
A E 20
B 6 D
20 C
13
B 6 D
13 C
Naïve Algorithm for MST
(Using Exhaustive Search)
MST Empty-Graph
cost
For each subgraph G’ = (V, E’) of G = (V, E) do {
1. Check that G’ is connected
2. Compute cost c of G’
3. If c < cost then {
3.1 MST G’
3.2 cost c }}
What is the complexity “in words” of the algorithm?
“the number of subgraphs” “cost of computing Steps 1-3”
How many subgraphs are there?
2|E|
This is bad!
The Prim Algorithm
// input: a graph G
// output: E: a MST for G
1. Select a starting node, v
2. T {v} //the nodes in the MST
3. E {} //the edges in the MST
4. While not all nodes in G are in the T do
3.1 Choose the edge v’ in G − T such that there is a v in T:
weight(v,v’) is the minimum in
{weight(u,w) : w in G − T and u in T}
3.2 T T {v’}
3.3 E E {(v,v’)}
5. return E
Complexity: - O((|E|+|V|)log2|E|)
- In class we show O(|E||V|)
Why does it works?
Property: Suppose that we divide the nodes of a graph
G = (V, E) in two groups V, V’:
T
G-T
12
7 22
20
2
5 6 66
13 10
12
A E
20
2 12 3
B 6 D
13 C
6
F
•|V| = 6
•|E| = 8
•A tree with |V| nodes has |V|-1 edges
The Kruskal Algorithm
// input: a graph G with n nodes and m edges
// output: E: a MST for G
1. EG[1..m] Sort the m edges in G in increasing weight order
2. E {} //the edges in the MST
3. i 1 //counter for EG
4. While |E| < n - 1 do
if adding EG[i] to E does not add a cycle then
E E {EG[i]}
ii+1
5. return E
Is this algorithm Greedy?
Yes
Complexity: O(|E|log2 |E|)
Why Does the Kruskal Algorithm Works?
• 010:
9.1: 3, 6.b, 9 (just explain)
9.2: 1.a, 2.a, 5
• 011:
9.1: 2, 6.a, 9.a
9.2: 1.b, 2.d, 4