-
Notifications
You must be signed in to change notification settings - Fork 1
/
Kruskal’s Minimum Spanning Tree Algorithm.cpp
69 lines (58 loc) · 1.24 KB
/
Kruskal’s Minimum Spanning Tree 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
#include<bits/stdc++.h>
using namespace std;
class Edge{
public:
int u, v, w;
Edge(int u, int v, int w){
this->u = u;
this->v = v;
this->w = w;
}
};
class Graph{
private:
int n;
int e;
vector<Edge> edges;
int find(int num, vector<int> &parent){
if(parent[num] == -1)
return num;
return find(parent[num], parent);
}
public:
Graph(int n, int e){
this->n = n;
this->e = e;
}
void addEdge(int u, int v, int w){
edges.push_back(Edge(u, v, w));
}
int mst(){
int res = 0, k = n - 1;
vector<int> parent(n, -1);
sort(edges.begin(), edges.end(), [&](Edge &a, Edge &b){
return a.w < b.w;
});
for(int i = 0; i < e && k; i++){
int a = find(edges[i].u, parent);
int b = find(edges[i].v, parent);
if(a == b)
continue;
parent[b] = a;
res += edges[i].w;
k--;
}
return res;
}
};
int main(){
int n, e, u, v, w;
cin >> n >> e;
Graph g(n, e);
for(int i = 0; i < e; i++){
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
cout << g.mst() << endl;
return 0;
}