-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumSpanningTree.cpp
More file actions
71 lines (61 loc) · 1.71 KB
/
minimumSpanningTree.cpp
File metadata and controls
71 lines (61 loc) · 1.71 KB
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
#include <bits/stdc++.h>
using namespace std;
/************************************************************************************************/
int const N = 1e5 + 10;
int parent[N];
int sz[N];
bool cmp(pair<int, pair<int, int>>a, pair<int, pair<int, int>>b) {
// if(a.second.second!=b.second.second){
return a.second.second < b.second.second;
}
void make(int v) {
parent[v] = v;
sz[v] = 1;
}
int find(int v) {
if (parent[v] == v) {
return v;
}
return parent[v] = find(parent[v]);
}
void Union(int a, int b) {
int parentOfa = find(a);
int parentOfb = find(b);
if (parentOfa != parentOfb) {
if (sz[a] < sz[b]) {
swap(parentOfa, parentOfb);
}
parent[parentOfb] = parentOfa;
sz[parentOfa] += sz[parentOfb];
}
}
void solve() {
int nodes, edges;
vector<pair<int, pair<int, int>>>graph;
cin >> nodes >> edges;
for (int i = 0; i < edges; i++) {
int u, v, w;
cin >> u >> v >> w;
graph.push_back({u, {v, w}});
}
sort(graph.begin(), graph.end(), cmp);
for (int i = 1; i <= nodes; i++) {
make(i);
}
int total=0;
for (auto it : graph) {
int u, v;
u = it.first, v = it.second.first;
if (find(u) == find(v)) {
continue;
}
Union(u, v);
total+=it.second.second;
cout << it.first << " " << it.second.first << " " << it.second.second << endl;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
}