Prims Algorithm: Difference between revisions

From Rice Wiki
No edit summary
(:q)
Line 24: Line 24:


= Proof: Greedy =
= Proof: Greedy =
== Suboptimality ==
Given MST tree for the graph G
<math>
OPT = \text{set of edges}
</math>
where the number of edges is <math>n - 1</math>, the weight of edges is
minimum, and the tree is spanning.
Consider <math>(x,y)</math>, where X is a leaf node.
Prove that <math>A = OPT - (x, y)</math> is a MST for the subproblem
<math>G - X</math>
By contradiction, assume that <math>A</math> is not optimal. There must
be <math>B</math> such that
<math>
w(B) < w(A)
</math>
Adding the edge (x, y) back to both graphs
<math>B + (x, y)</math> is a viable tree.
<math>
w(B + w(x,y)) < w(A + w(x,y)) = w(OPT)
</math>
Therefore, OPT is not the optimal solution.
By contradiction, <math>A</math> must be optimal.


[[Category:Algorithms]]
[[Category:Algorithms]]

Revision as of 01:29, 8 March 2024

Approach: Greedy

See Minimum_Spanning_Tree

Implementation

for each u in V:
    key[u] = infinity   // cost array
    pi[u] = infinity    // from array
Q = new PriorityQueue(V)
key[root] = 0
while Q is not empty:
    u = extractMin(Q)
    # Reduce nodes
    for v in adj[u]:
        if v in Q and w[u,v] < key[v]:
            key[v] = w[u,v]

Analysis

Priority queue is slower than array when the graph is dense, so sometimes it's better to use Dijsktra's algorithm.

Proof: Greedy