File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ class Edge implements Comparable<Edge > {
6+ int u, v, weight;
7+
8+ public Edge (int u , int v , int weight ) {
9+ this . u = u;
10+ this . v = v;
11+ this . weight = weight;
12+ }
13+
14+ @Override
15+ public int compareTo (Edge o ) {
16+ return this . weight - o. weight;
17+ }
18+ }
19+
20+ public class Main {
21+
22+ static int [] parent;
23+
24+ public static void main (String [] args ) throws IOException {
25+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
26+ int N = Integer . parseInt(br. readLine());
27+
28+ List<Edge > edges = new ArrayList<> ();
29+ for (int i = 0 ; i < N ; i++ ) {
30+ StringTokenizer st = new StringTokenizer (br. readLine());
31+ for (int j = 0 ; j < N ; j++ ) {
32+ int weight = Integer . parseInt(st. nextToken());
33+ if (i < j) {
34+ edges. add(new Edge (i, j, weight));
35+ }
36+ }
37+ }
38+
39+ Collections . sort(edges);
40+
41+ parent = new int [N ];
42+ for (int i = 0 ; i < N ; i++ ) parent[i] = i;
43+
44+ long cost = 0 ;
45+ int count = 0 ;
46+
47+ for (Edge edge : edges) {
48+ if (union(edge. u, edge. v)) {
49+ cost += edge. weight;
50+ count++ ;
51+ if (count == N - 1 ) break ;
52+ }
53+ }
54+
55+ System . out. println(cost);
56+ }
57+
58+ static int find (int x ) {
59+ if (parent[x] == x) return x;
60+ return parent[x] = find(parent[x]);
61+ }
62+
63+ static boolean union (int x , int y ) {
64+ x = find(x);
65+ y = find(y);
66+
67+ if (x != y) {
68+ parent[y] = x;
69+ return true ;
70+ }
71+ return false ;
72+ }
73+ }
74+ ```
You can’t perform that action at this time.
0 commit comments