1+ import java .util .*;
2+
3+ class Edge implements Comparable <Edge > {
4+
5+ private int distance ;
6+ private int nodeA ;
7+ private int nodeB ;
8+
9+ public Edge (int distance , int nodeA , int nodeB ) {
10+ this .distance = distance ;
11+ this .nodeA = nodeA ;
12+ this .nodeB = nodeB ;
13+ }
14+
15+ public int getDistance () {
16+ return this .distance ;
17+ }
18+
19+ public int getNodeA () {
20+ return this .nodeA ;
21+ }
22+
23+ public int getNodeB () {
24+ return this .nodeB ;
25+ }
26+
27+ // 거리(비용)가 짧은 것이 높은 우선순위를 가지도록 설정
28+ @ Override
29+ public int compareTo (Edge other ) {
30+ if (this .distance < other .distance ) {
31+ return -1 ;
32+ }
33+ return 1 ;
34+ }
35+ }
36+
37+ public class Main {
38+
39+ // 노드의 개수(V)와 간선(Union 연산)의 개수(E)
40+ // 노드의 개수는 최대 100,000개라고 가정
41+ public static int v , e ;
42+ public static int [] parent = new int [100001 ]; // 부모 테이블 초기화하기
43+ // 모든 간선을 담을 리스트와, 최종 비용을 담을 변수
44+ public static ArrayList <Edge > edges = new ArrayList <>();
45+ public static int result = 0 ;
46+
47+ // 특정 원소가 속한 집합을 찾기
48+ public static int findParent (int x ) {
49+ // 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
50+ if (x == parent [x ]) return x ;
51+ return parent [x ] = findParent (parent [x ]);
52+ }
53+
54+ // 두 원소가 속한 집합을 합치기
55+ public static void unionParent (int a , int b ) {
56+ a = findParent (a );
57+ b = findParent (b );
58+ if (a < b ) parent [b ] = a ;
59+ else parent [a ] = b ;
60+ }
61+
62+ public static void main (String [] args ) {
63+ Scanner sc = new Scanner (System .in );
64+
65+ v = sc .nextInt ();
66+ e = sc .nextInt ();
67+
68+ // 부모 테이블상에서, 부모를 자기 자신으로 초기화
69+ for (int i = 1 ; i <= v ; i ++) {
70+ parent [i ] = i ;
71+ }
72+
73+ // 모든 간선에 대한 정보를 입력 받기
74+ for (int i = 0 ; i < e ; i ++) {
75+ int a = sc .nextInt ();
76+ int b = sc .nextInt ();
77+ int cost = sc .nextInt ();
78+ // 비용순으로 정렬하기 위해서 튜플의 첫 번째 원소를 비용으로 설정
79+ edges .add (new Edge (cost , a , b ));
80+ }
81+
82+ // 간선을 비용순으로 정렬
83+ Collections .sort (edges );
84+
85+ // 간선을 하나씩 확인하며
86+ for (int i = 0 ; i < edges .size (); i ++) {
87+ int cost = edges .get (i ).getDistance ();
88+ int a = edges .get (i ).getNodeA ();
89+ int b = edges .get (i ).getNodeB ();
90+ // 사이클이 발생하지 않는 경우에만 집합에 포함
91+ if (findParent (a ) != findParent (b )) {
92+ unionParent (a , b );
93+ result += cost ;
94+ }
95+ }
96+
97+ System .out .println (result );
98+ }
99+ }
0 commit comments