This repository was archived by the owner on Feb 13, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ package BOJ .boj6497 ;
2
+
3
+ import java .util .PriorityQueue ;
4
+ import java .util .Scanner ;
5
+
6
+ public class Main {
7
+ static int [] parents ;
8
+ static PriorityQueue <Node > pq = new PriorityQueue <>((o1 , o2 ) -> o1 .c - o2 .c );
9
+
10
+ static class Node {
11
+ int x ;
12
+ int y ;
13
+ int c ;
14
+
15
+ public Node (int x , int y , int c ) {
16
+ this .x = x ;
17
+ this .y = y ;
18
+ this .c = c ;
19
+ }
20
+ }
21
+
22
+ public static void main (String [] args ) {
23
+ Scanner sc = new Scanner (System .in );
24
+
25
+ while (true ) {
26
+ int n = sc .nextInt (); // 집의 수
27
+ int e = sc .nextInt (); // 길의 수
28
+
29
+ if (n == 0 && e == 0 ) {
30
+ break ;
31
+ }
32
+
33
+ parents = new int [n + 1 ];
34
+ for (int i = 1 ; i < n + 1 ; i ++) {
35
+ parents [i ] = i ;
36
+ }
37
+ int total = 0 ;
38
+ for (int i = 0 ; i < e ; i ++) {
39
+ int x = sc .nextInt ();
40
+ int y = sc .nextInt ();
41
+ int c = sc .nextInt ();
42
+ pq .add (new Node (x , y , c ));
43
+ total += c ;
44
+ }
45
+ int answer = 0 ;
46
+ while (!pq .isEmpty ()) {
47
+ Node cur = pq .poll ();
48
+ int px = find (cur .x );
49
+ int py = find (cur .y );
50
+ if (px == py ) continue ;
51
+ union (px , py );
52
+ answer += cur .c ;
53
+ }
54
+
55
+ System .out .println (total - answer );
56
+ }
57
+ }
58
+ public static int find (int x ) {
59
+ if (x == parents [x ]) return x ;
60
+ return parents [x ] = find (parents [x ]);
61
+ }
62
+
63
+ public static void union (int x , int y ) {
64
+ if (x < y ) parents [y ] = parents [x ];
65
+ else parents [x ] = parents [y ];
66
+ }
67
+ }
You can’t perform that action at this time.
0 commit comments