Skip to content

Commit

Permalink
Merge pull request #2524 from abhaysaini/patch-2
Browse files Browse the repository at this point in the history
Create Kruskal's ALgorithm.cpp
  • Loading branch information
fineanmol authored Oct 5, 2022
2 parents 80c1976 + 0612ae6 commit 555704d
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions Program's_Contributed_By_Contributors/C++/Kruskal's ALgorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int u;
int v;
int weight;
Node(int first, int second, int wt)
{
u = first;
v = second;
weight = wt;
}
};
bool cmp(Node a, Node b)
{
return a.weight < b.weight;
}

int findPar(int u, vector<int> &parent)
{
if (u == parent[u])
return u;
return parent[u] = findPar(parent[u], parent);
}

void unionn(int u, int v, vector<int> &parent, vector<int> &rank)
{
u = findPar(u, parent);
v = findPar(v, parent);
if (rank[u] < rank[v])
{
parent[u] = v;
}
else if (rank[v] < rank[u])
{
parent[v] = u;
}
else
{
parent[v] = u;
rank[u]++;
}
}

int main()
{
int n, m;
cin >> n >> m;
vector<Node> v;
for (int i = 0; i < m; i++)
{
int x, y, w;
cin >> x >> y >> w;
v.push_back(Node(x, y, w));
}
sort(v.begin(), v.end(), cmp);
vector<int> parent(n, 0), rank(n, 0);
for (int i = 0; i < n; i++)
{
parent[i] = i;
}

int cost = 0;
vector<pair<int,int>> mst;

for (auto it : v)
{
if (findPar(it.v, parent) != findPar(it.u, parent))
{
cost += it.weight;
mst.push_back({it.u, it.v});
unionn(it.u, it.v, parent, rank);
}
}
cout << cost << endl;
for (auto it : mst)
{
cout << it.first << " - " << it.second << endl;
}
return 0;
}

0 comments on commit 555704d

Please sign in to comment.