File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .io .*;
2
+ import java .util .*;
3
+
4
+ public class Main {
5
+ public static int [] parent ;
6
+
7
+ public static void main (String [] args ) throws IOException {
8
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
9
+ StringTokenizer st = new StringTokenizer (br .readLine ());
10
+ int N = Integer .parseInt (st .nextToken ());
11
+ int M = Integer .parseInt (st .nextToken ());
12
+ parent = new int [N +1 ];
13
+ for (int i =1 ; i <=N ; i ++) {
14
+ parent [i ] = i ;
15
+ }
16
+ PriorityQueue <int []> pq = new PriorityQueue <>((o1 , o2 ) -> Integer .compare (o1 [2 ], o2 [2 ]));
17
+ for (int i =0 ; i <M ; i ++) {
18
+ st = new StringTokenizer (br .readLine ());
19
+ int A = Integer .parseInt (st .nextToken ());
20
+ int B = Integer .parseInt (st .nextToken ());
21
+ int C = Integer .parseInt (st .nextToken ());
22
+ pq .offer (new int []{A , B , C });
23
+ }
24
+ long totalCost = 0 ;
25
+ int maxCost = 0 ;
26
+ while (!pq .isEmpty ()) {
27
+ int [] edge = pq .poll ();
28
+ int v1 = edge [0 ];
29
+ int v2 = edge [1 ];
30
+ int cost = edge [2 ];
31
+
32
+ // 사이클이 없으면 연결 후 비용 더하기
33
+ if (union (v1 , v2 )) {
34
+ totalCost += cost ;
35
+ maxCost = cost ;
36
+ }
37
+ }
38
+ System .out .println (totalCost - maxCost );
39
+ }
40
+
41
+ public static int find (int x ) {
42
+ if (parent [x ] == x ) {
43
+ return x ;
44
+ }
45
+ parent [x ] = find (parent [x ]);
46
+ return parent [x ];
47
+ }
48
+
49
+ public static boolean union (int x , int y ) {
50
+ x = find (x );
51
+ y = find (y );
52
+ if (x == y ) {
53
+ return false ;
54
+ }
55
+ parent [y ] = x ;
56
+ return true ;
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments