-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminSpanningTree.cpp
More file actions
59 lines (49 loc) · 912 Bytes
/
minSpanningTree.cpp
File metadata and controls
59 lines (49 loc) · 912 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int par[1010];
int find(int v){
if(v == par[v]) return v;
return par[v] = find(par[v]);
}
int merge(int u, int v){
u = find(u), v = find(v);
if(u == v) return 0;
par[u] = v;
return 1;
}
struct edge{
int val;
int s, e;
edge(){}
edge(int x, int y, int z) : val(x), s(y), e(z) {}
};
vector<edge> v;
bool comp(edge &a, edge &b){
return a.val < b.val;
}
int mst(int n){
int cnt = 0, ret = 0;
for(int i=0; i<=n; i++) par[i] = i;
for(int i=0; i<v.size(); i++){
if(merge(v[i].s, v[i].e)){
ret+=v[i].val;
cnt++;
}
if(cnt == n-1) break;
}
return ret;
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int n, m, k; cin >> n >> m >> k;
v.clear();
for(int i=0; i<m; i++){
int c; int s, e;
cin >> c >> s >> e;
v.push_back({c, s, e});
}
int a, b;
sort(v.begin(), v.end(), comp);
a = mst(n);
cout << a;
}