Skip to content

Commit 26a98e5

Browse files
Create kruskalAlgorithm.cpp
1 parent 160708f commit 26a98e5

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Graphs/kruskalAlgorithm.cpp

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
const int MAX = 1e4 + 5;
6+
int id[MAX], nodes, edges;
7+
pair <long long, pair<int, int> > p[MAX];
8+
9+
// Kruskal's Algorithm: https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
10+
11+
void initialize()
12+
{
13+
for(int i = 0;i < MAX;++i)
14+
id[i] = i;
15+
}
16+
17+
int root(int x)
18+
{
19+
while(id[x] != x)
20+
{
21+
id[x] = id[id[x]];
22+
x = id[x];
23+
}
24+
return x;
25+
}
26+
27+
void union1(int x, int y)
28+
{
29+
int p = root(x);
30+
int q = root(y);
31+
id[p] = id[q];
32+
}
33+
34+
long long kruskal(pair<long long, pair<int, int> > p[])
35+
{
36+
int x, y;
37+
long long cost, minimumCost = 0;
38+
for(int i = 0;i < edges;++i)
39+
{
40+
// Selecting edges one by one in increasing order from the beginning
41+
x = p[i].second.first;
42+
y = p[i].second.second;
43+
cost = p[i].first;
44+
// Check if the selected edge is creating a cycle or not
45+
if(root(x) != root(y))
46+
{
47+
minimumCost += cost;
48+
union1(x, y);
49+
}
50+
}
51+
return minimumCost;
52+
}
53+
54+
int main()
55+
{
56+
// Input
57+
int x, y;
58+
long long weight, cost, minimumCost;
59+
initialize();
60+
cin >> nodes >> edges;
61+
for(int i = 0;i < edges;++i)
62+
{
63+
cin >> x >> y >> weight;
64+
p[i] = make_pair(weight, make_pair(x, y));
65+
}
66+
67+
// Sort the edges in the ascending order
68+
sort(p, p + edges);
69+
minimumCost = kruskal(p);
70+
cout << minimumCost << endl;
71+
return 0;
72+
}

0 commit comments

Comments
 (0)