0% found this document useful (0 votes)
26 views4 pages

Kruskal's Algorithm for Students

The document describes Kruskal's algorithm for finding the minimum spanning tree of a graph. It includes code for implementing Kruskal's algorithm using disjoint set union with path compression and rank by union. The code takes a graph as input, sorts the edges by weight, and uses union-find to check if adding an edge creates a cycle in the MST being constructed.

Uploaded by

pankajrathod4510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views4 pages

Kruskal's Algorithm for Students

The document describes Kruskal's algorithm for finding the minimum spanning tree of a graph. It includes code for implementing Kruskal's algorithm using disjoint set union with path compression and rank by union. The code takes a graph as input, sorts the edges by weight, and uses union-find to check if adding an edge creates a cycle in the MST being constructed.

Uploaded by

pankajrathod4510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

// Name : Dhiraj Patil

// Roll no : 13

/ Kruskal’s Algorithm

#include <bits/stdc++.h>
using namespace std;

// path compression + rank by union


class DSU
{
int* parent;
int* rank;

public:
DSU(int n)
{

parent = new int[n];


rank = new int[n];

for (int i = 0; i < n; i++)


{
parent[i] = -1;
rank[i] = 1;
}
}

int find(int i)
{
if (parent[i] == -1)
return i;

return parent[i] = find(parent[i]);


}

// Union function
void unite(int x, int y)
{

int s1 = find(x);
int s2 = find(y);

if (s1 != s2) {
if (rank[s1] < rank[s2])
{
parent[s1] = s2;
}

else if (rank[s1] > rank[s2])

{
parent[s2] = s1;
}
else {

parent[s2] = s1;
rank[s1] += 1;

}
}
}
};
class Graph
{

vector<vector<int> > edgelist;


int V;

public:
Graph(int V) { this->V = V; }

// Function to add edge in a graph


void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}

void kruskals_mst()
{
// Sort all edges

sort([Link](), [Link]());
DSU s(V);
int ans = 0;
cout << "Following are the edges in the constructed MST"<< endl;

for (auto edge : edgelist)


{
int w = edge[0];
int x = edge[1];
int y = edge[2];

// Take this edge in MST if it does not forms a cycle


if ([Link](x) != [Link](y))
{
[Link](x, y);
ans += w;

cout << x << " -- " << y << " == " << w << endl;
}
}
cout << "Minimum Cost Spanning Tree:" << ans;
}
};

int main()
{

Graph g(4);
[Link](0, 1, 10);
[Link](1, 3, 15);
[Link](2, 3, 4);
[Link](2, 0, 6);
[Link](0, 3, 5);
g.kruskals_mst();
return 0;
}

Output :-

You might also like