-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskal.cpp
72 lines (54 loc) · 1.12 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
64
65
66
67
68
69
70
71
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int parent[10001];
struct edge {
int u,v,w;
edge(int u, int v, int w) {
this->u = u;
this->v = v;
this->w = w;
}
};
int find(int u) {
if(u == parent[u])
{
return u;
}
return parent[u] = find(parent[u]);
}
void merge(int u, int v) {
u = find(u);
v = find(v);
parent[v] = u;
}
int compare_comp(const edge& a, const edge& b) {
return a.w < b.w;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
vector<edge> v;
int V,E;
long long ans = 0;
cin >> V >> E;
int A,B,C;
for(int i = 1; i <= V; i++)
parent[i] = i;
for(int i = 0; i < E; i++) {
cin >> A >> B >> C;
v.push_back(edge(A, B, C));
}
sort(v.begin(), v.end(), compare_comp);
for(auto n : v) {
if(find(n.v) != find(n.u)) {
cout<<n.w<<" ";
merge(n.u, n.v);
ans += n.w;
}
}
cout<<ans<<"\n";
return 0;
}