2026-01-13 22:44:15 +09:00

69 lines
1.4 KiB
Java

import java.util.*;
public class _1647_1 {
static int[] parents;
static int[] rank;
static int find(int x) {
if(x != parents[x]) return parents[x] = find(parents[x]);
return x;
}
static void union(int x, int y) {
x = find(x);
y = find(y);
if(x==y) return;
if(rank[x] < rank[y]) {
int temp = x;
x = y;
y = temp;
}
if(rank[x] == rank[y]) rank[x]++;
parents[y] = x;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), M = sc.nextInt();
if(N==2) {
System.out.println(0);
return;
}
ArrayList<int[]> edges = new ArrayList<>();
for(int i=0; i<M; i++) {
int A = sc.nextInt(), B = sc.nextInt(), C = sc.nextInt();
int[] edge = {A, B, C};
edges.add(edge);
}
sc.close();
edges.sort((a,b) -> a[2] - b[2]);
parents = new int[N+1];
for(int i=1; i<=N; i++) parents[i] = i;
rank = new int[N+1];
int cnt = 0, ans = 0;
for (int[] edge : edges) {
int a = edge[0], b = edge[1], c = edge[2];
if(find(a) == find(b)) continue;
union(a, b);
cnt += 1;
ans += c;
if(cnt == N-2) break;
}
System.out.println(ans);
}
}