File tree 1 file changed +64
-0
lines changed
1 file changed +64
-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
+ StringBuilder sb = new StringBuilder ();
10
+ while (true ) {
11
+ StringTokenizer st = new StringTokenizer (br .readLine ());
12
+ int N = Integer .parseInt (st .nextToken ());
13
+ int M = Integer .parseInt (st .nextToken ());
14
+ if (N == 0 && M == 0 ) {
15
+ System .out .print (sb );
16
+ return ;
17
+ }
18
+ parent = new int [N + 1 ];
19
+ for (int i = 0 ; i < N ; i ++) {
20
+ parent [i ] = i ;
21
+ }
22
+ PriorityQueue <int []> pq = new PriorityQueue <>((o1 , o2 ) -> Integer .compare (o1 [2 ], o2 [2 ]));
23
+ long totalCost = 0 ;
24
+ for (int i = 0 ; i < M ; i ++) {
25
+ st = new StringTokenizer (br .readLine ());
26
+ int A = Integer .parseInt (st .nextToken ());
27
+ int B = Integer .parseInt (st .nextToken ());
28
+ int C = Integer .parseInt (st .nextToken ());
29
+ totalCost += C ;
30
+ pq .offer (new int []{A , B , C });
31
+ }
32
+ long minCost = 0 ;
33
+ while (!pq .isEmpty ()) {
34
+ int [] edge = pq .poll ();
35
+ int v1 = edge [0 ];
36
+ int v2 = edge [1 ];
37
+ int cost = edge [2 ];
38
+
39
+ if (union (v1 , v2 )) {
40
+ minCost += cost ;
41
+ }
42
+ }
43
+ sb .append (totalCost - minCost ).append ('\n' );
44
+ }
45
+ }
46
+
47
+ public static int find (int x ) {
48
+ if (parent [x ] == x ) {
49
+ return x ;
50
+ }
51
+ parent [x ] = find (parent [x ]);
52
+ return parent [x ];
53
+ }
54
+
55
+ public static boolean union (int x , int y ) {
56
+ x = find (x );
57
+ y = find (y );
58
+ if (x == y ) {
59
+ return false ;
60
+ }
61
+ parent [y ] = x ;
62
+ return true ;
63
+ }
64
+ }
You can’t perform that action at this time.
0 commit comments