1 //克鲁斯卡尔 2 #include <iostream> 3 #include <algorithm> 4 5 using namespace std; 6 const int maxn = 50000 + 5; 7 8 struct node{ 9 int x, y; 10 int len; 11 }g[maxn]; 12 13 bool cmp(node x, node y){ 14 return x.len < y.len; 15 } 16 17 int fa[maxn]; 18 19 int Find(int x){ 20 if (x == fa[x]) 21 return x; 22 else 23 return fa[x] = Find(fa[x]); 24 } 25 26 27 int main(){ 28 ios::sync_with_stdio(false); 29 30 int n, m; 31 cin >> n >> m; 32 for (int i = 0; i <= n; i++){ 33 fa[i] = i; 34 } 35 36 int a, b, c; 37 for (int i = 0; i < m; i++){ 38 cin >> a >> b >> c; 39 g[i].x = a; 40 g[i].y = b; 41 g[i].len = c; 42 } 43 int ans = 0; 44 sort(g, g + m, cmp); 45 for (int i = 0; i < m; i++){ 46 int u, v; 47 u = g[i].x; 48 v = g[i].y; 49 int u1 = Find(u); 50 int v1 = Find(v); 51 if (u1 != v1){ 52 fa[v1] = u1; 53 ans += g[i].len; 54 } 55 } 56 cout << ans << endl; 57 return 0; 58 }