-
Notifications
You must be signed in to change notification settings - Fork 3
/
kruskal.cpp
63 lines (57 loc) · 1.34 KB
/
kruskal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1e4 + 5;
int id[MAX], n, e;
pair <long long, pair<int, int> > p[MAX]; //creating an array of pair of pair
int root(int x)
{
while(id[x] != x)
{
id[x] = id[id[x]];
x = id[x];
}
return x;
}
void union1(int x, int y)
{
int p = root(x);
int q = root(y);
id[p] = id[q];
}
long long kruskal(pair<long long, pair<int, int> > p[])
{
int x, y;
long long cost, minimumcost = 0;
for(int i = 0;i < e;++i)
{
// Selecting edges one by one in increasing order from the beginning
x = p[i].second.first;
y = p[i].second.second;
cost = p[i].first;
// Check if the selected edge is creating a cycle or not
if(root(x) != root(y))
{
minimumcost += cost;
union1(x, y);
}
}
return minimumcost;
}
int main()
{
int x, y;
long long weight, cost, minimumcost;
for(int i = 0;i < MAX;++i)
id[i] = i;
cin >> n >> e;
for(int i = 0;i < e;++i)
{
cin >> x >> y >> weight;
p[i] = make_pair(weight, make_pair(x, y));
}
// Sort the edges in the ascending order
sort(p, p + e);
minimumcost = kruskal(p);
cout << minimumcost << endl;
return 0;
}