forked from anishpatil31/CP-Templates-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKruskal Algorithm.cpp
82 lines (64 loc) · 1.28 KB
/
Kruskal Algorithm.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Code for Kruskal Algorithm for finding minimum spanning tree.
// Time Complexity - O(m * log n) where m is the number of edges and n is the number of nodes in graph.
int parent[LIM], size[LIM];
int findSet(int v)
{
if (v == parent[v])
return v;
return parent[v] = findSet(parent[v]);
}
void makeSet(int v)
{
parent[v] = v;
size[v] = 1;
}
void unionSets(int a, int b)
{
a = findSet(a);
b = findSet(b);
if (a != b)
{
if (size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
}
}
struct Edge
{
int u, v, w;
bool operator < (Edge& e)
{
return w < e.w;
}
};
void solve()
{
int n, m;
cin >> n >> m;
vector<Edge> edges, mst;
int cost = 0;
for (int i = 0; i <= n; ++i)
makeSet(i);
for (int i = 0; i < m; ++i)
{
int u, v, w;
cin >> u >> v >> w;
edges.pb({u, v, w});
}
sort(edges.begin(), edges.end());
for (auto e : edges)
{
if (findSet(e.u) != findSet(e.v))
{
cost += e.w;
mst.push_back(e);
unionSets(e.u, e.v);
}
if (mst.size() == n - 1)
break;
}
if (mst.size() != n - 1)
// no mst possible
return;
}