Home BOJ. MST (Minimum Spanning Tree) (1197)
Post
Cancel

BOJ. MST (Minimum Spanning Tree) (1197)

[Link] https://www.acmicpc.net/problem/1197


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static int[] seg;
	static int[] orig;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int[] arr = getArr();
		ArrayList<Edge> edges = new ArrayList<>();
		PriorityQueue<Edge> pq = new PriorityQueue<>((l, r) -> l.val - r.val);
		int v = arr[0], e = arr[1];

		for(int i = 0; i < e; i++) {
			arr = getArr();
			int a = arr[0] - 1, b = arr[1] - 1, c = arr[2];
			if(a > b) {
				int tmp = a;
				a = b;
				b = a;
			}
			pq.add(new Edge(a, b, c));
		}

		int ans = 0;
		int[] parents = new int[v];
		for(int i = 0; i < v; i++) parents[i] = i;
		while(!pq.isEmpty()) {
			Edge cur = pq.poll();
			int p1 = getParent(parents, cur.v1);
			int p2 = getParent(parents, cur.v2);
			if(p1 == p2) continue;
			if(p1 < p2) parents[p2] = p1;
			else parents[p1] = p2;
			ans += cur.val;
		}
		print(ans);
	}

	static int getParent(int[] arr, int idx) {
		if(idx == arr[idx]) return idx;
		else return arr[idx] = getParent(arr, arr[idx]);
	}

	static class Edge {
		int v1;
		int v2;
		int val;
		public Edge(int v1, int v2, int val) { this.v1 = v1; this.v2 = v2; this.val = val; }
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.