c++ mst kruskal

The Kruskal's algorithm is a popular algorithm used to find the Minimum Spanning Tree (MST) of a graph. It is an efficient algorithm that works well for both dense and sparse graphs. The algorithm follows these steps:

  1. Sort the edges: The first step is to sort all the edges of the graph in non-decreasing order of their weights. This can be done using any sorting algorithm, such as quicksort or mergesort.

  2. Initialize an empty MST: Create an empty set to store the edges of the MST.

  3. Iterate through the sorted edges: Starting from the smallest edge, iterate through each edge in the sorted list.

  4. Check for a cycle: For each edge, check if including it in the MST will create a cycle. This can be done by using a disjoint set data structure. If adding the edge does not create a cycle, include it in the MST.

  5. Update the disjoint set: If an edge is included in the MST, merge the sets of the two endpoints of the edge in the disjoint set data structure.

  6. Repeat until MST is complete: Repeat steps 4 and 5 until the MST contains V-1 edges, where V is the number of vertices in the graph.

  7. Output the MST: Once the MST is complete, output the set of edges that make up the MST.

To give you a better understanding, here is an example implementation of Kruskal's algorithm in C++:

#include <iostream>
#include <vector>
#include <algorithm>

// Data structure to represent an edge
struct Edge {
    int src, dest, weight;
};

// Data structure to represent a disjoint set
struct DisjointSet {
    std::vector<int> parent, rank;
    DisjointSet(int n) {
        parent.resize(n);
        rank.resize(n);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            rank[i] = 0;
        }
    }
    int find(int i) {
        if (i != parent[i])
            parent[i] = find(parent[i]);
        return parent[i];
    }
    void unionSet(int x, int y) {
        int xRoot = find(x);
        int yRoot = find(y);
        if (rank[xRoot] < rank[yRoot])
            parent[xRoot] = yRoot;
        else if (rank[xRoot] > rank[yRoot])
            parent[yRoot] = xRoot;
        else {
            parent[yRoot] = xRoot;
            rank[xRoot]++;
        }
    }
};

// Function to find MST using Kruskal's algorithm
std::vector<Edge> kruskalMST(std::vector<Edge>& edges, int V) {
    std::vector<Edge> result;

    // Sort edges in non-decreasing order of their weight
    std::sort(edges.begin(), edges.end(), [](Edge a, Edge b) {
        return a.weight < b.weight;
    });

    // Create a disjoint set
    DisjointSet ds(V);

    // Iterate through all sorted edges
    for (const auto& edge : edges) {
        int src = edge.src;
        int dest = edge.dest;
        int srcRoot = ds.find(src);
        int destRoot = ds.find(dest);

        // Check if including the edge forms a cycle
        if (srcRoot != destRoot) {
            result.push_back(edge);
            ds.unionSet(srcRoot, destRoot);
        }
    }

    return result;
}

int main() {
    // Example usage
    int V = 4; // Number of vertices in the graph
    std::vector<Edge> edges = {
        {0, 1, 10},
        {0, 2, 6},
        {0, 3, 5},
        {1, 3, 15},
        {2, 3, 4}
    };

    std::vector<Edge> mst = kruskalMST(edges, V);

    // Output the MST
    for (const auto& edge : mst) {
        std::cout << edge.src << " - " << edge.dest << " : " << edge.weight << std::endl;
    }

    return 0;
}

This implementation uses a disjoint set data structure to efficiently check for cycles and merge sets. The algorithm sorts the edges based on their weights and then iterates through them, adding edges to the MST if they don't create a cycle. The final MST is outputted at the end.

I hope this explanation and example code helps! Let me know if you have any further questions.