diff --git "a/Seol-JY/202506/25 BOJ G4 \354\265\234\354\206\214 \354\212\244\355\214\250\353\213\235 \355\212\270\353\246\254.md" "b/Seol-JY/202506/25 BOJ G4 \354\265\234\354\206\214 \354\212\244\355\214\250\353\213\235 \355\212\270\353\246\254.md" new file mode 100644 index 00000000..a3d1201a --- /dev/null +++ "b/Seol-JY/202506/25 BOJ G4 \354\265\234\354\206\214 \354\212\244\355\214\250\353\213\235 \355\212\270\353\246\254.md" @@ -0,0 +1,68 @@ +```java +import java.util.*; +import java.io.*; + +public class Main { + static int[] parent; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int V = Integer.parseInt(st.nextToken()); + int E = Integer.parseInt(st.nextToken()); + + List edgeList = new ArrayList<>(); + parent = new int[V + 1]; + + for (int i = 1; i <= V; i++) { + parent[i] = i; + } + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + int weight = Integer.parseInt(st.nextToken()); + edgeList.add(new Edge(a, b, weight)); + } + + edgeList.sort((e1, e2) -> Integer.compare(e1.weight, e2.weight)); + + int total = 0; + int count = 0; + + for (Edge edge : edgeList) { + if (find(edge.from) != find(edge.to)) { + union(edge.from, edge.to); + total += edge.weight; + count++; + if (count == V - 1) break; + } + } + + System.out.println(total); + } + + static int find(int x) { + if (parent[x] == x) return x; + return parent[x] = find(parent[x]); + } + + static void union(int a, int b) { + int rootA = find(a); + int rootB = find(b); + if (rootA != rootB) parent[rootB] = rootA; + } + + static class Edge { + int from, to, weight; + + Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } + } +} + +```