From f01f4bf99d53db3dc0e1eb346742a79cb8e4c48a Mon Sep 17 00:00:00 2001 From: LiiNi-coder <97495437+LiiNi-coder@users.noreply.github.com> Date: Sat, 6 Sep 2025 23:47:55 +0900 Subject: [PATCH] =?UTF-8?q?[20250906]=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=9D=B4=EC=9D=B8=ED=9D=AC?= 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" | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 "LiiNi-coder/202509/06 BOJ \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/LiiNi-coder/202509/06 BOJ \354\265\234\354\206\214 \354\212\244\355\214\250\353\213\235 \355\212\270\353\246\254.md" "b/LiiNi-coder/202509/06 BOJ \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..fd028c05 --- /dev/null +++ "b/LiiNi-coder/202509/06 BOJ \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,79 @@ +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class Main { + private static BufferedReader br; + private static int V, E; + private static ArrayList[] adj; + private static boolean[] visited; + private static class Edge implements Comparable { + int to, weight; + public Edge(int to, int weight) { + this.to = to; + this.weight = weight; + } + @Override + public int compareTo(Edge other) { + return this.weight - other.weight; + } + } + + public static void main(String[] args) throws IOException { + br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + V = Integer.parseInt(st.nextToken()); + E = Integer.parseInt(st.nextToken()); + adj = new ArrayList[V + 1]; + for (int i = 1; i <= V; i++) { + adj[i] = new ArrayList<>(); + } + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(br.readLine()); + int u = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + + adj[u].add(new Edge(v, w)); + adj[v].add(new Edge(u, w)); + } + + System.out.println(prim()); + } + + private static long prim() { + boolean[] visited = new boolean[V + 1]; + PriorityQueue pq = new PriorityQueue<>(); + long totalWeight = 0; + int visitedCount = 0; + + visited[1] = true; + visitedCount++; + for (Edge e : adj[1]) { + pq.add(e); + } + + while (!pq.isEmpty()) { + Edge edge = pq.poll(); + if (visited[edge.to]) continue; + visited[edge.to] = true; + totalWeight += edge.weight; + visitedCount++; + for (Edge e : adj[edge.to]) { + if (!visited[e.to]) { + pq.add(e); + } + } + if (visitedCount == V) break; + } + + return totalWeight; + } +} + +```