From bb88e29355af717d45fd1465f0dce8cf40e8b234 Mon Sep 17 00:00:00 2001 From: Jinyeong Seol Date: Wed, 25 Jun 2025 21:25:58 +0900 Subject: [PATCH] =?UTF-8?q?[20250625]=20BOJ=20/=20G4=20/=20=EC=B5=9C?= =?UTF-8?q?=EC=86=8C=20=EC=8A=A4=ED=8C=A8=EB=8B=9D=20=ED=8A=B8=EB=A6=AC=20?= =?UTF-8?q?/=20=EC=84=A4=EC=A7=84=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0\353\213\235 \355\212\270\353\246\254.md" | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 "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" 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; + } + } +} + +```