c++ competitive programming mst
To implement Prim's algorithm for finding the Minimum Spanning Tree (MST) in C++, follow these steps:
- Start with an arbitrary node as the initial vertex.
- Initialize a boolean array to track visited vertices and a vector to store the MST.
- Set the initial vertex distance to 0 and push it into a priority queue.
- While the priority queue is not empty, do the following:
- Extract the vertex with the minimum distance from the priority queue.
- Mark the vertex as visited.
- Iterate through its adjacent vertices:
- If the adjacent vertex is not visited and its edge weight is less than the current distance, update the distance and push it into the priority queue.
- Push the minimum distance vertex into the MST vector.
- The MST vector now contains the minimum spanning tree.