From a128b34d1552f260fe5d5ef4252b7b060bceb5d2 Mon Sep 17 00:00:00 2001 From: suyeun84 <81475092+suyeun84@users.noreply.github.com> Date: Fri, 22 Aug 2025 15:18:54 +0900 Subject: [PATCH] =?UTF-8?q?[20250822]=20BOJ=20/=20G4=20/=20=EB=8F=84?= =?UTF-8?q?=EC=8B=9C=20=EA=B1=B4=EC=84=A4=20/=20=EA=B9=80=EC=88=98?= =?UTF-8?q?=EC=97=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\354\213\234 \352\261\264\354\204\244.md" | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 "suyeun84/202508/22 BOJ G4 \353\217\204\354\213\234 \352\261\264\354\204\244.md" diff --git "a/suyeun84/202508/22 BOJ G4 \353\217\204\354\213\234 \352\261\264\354\204\244.md" "b/suyeun84/202508/22 BOJ G4 \353\217\204\354\213\234 \352\261\264\354\204\244.md" new file mode 100644 index 00000000..fa2693ee --- /dev/null +++ "b/suyeun84/202508/22 BOJ G4 \353\217\204\354\213\234 \352\261\264\354\204\244.md" @@ -0,0 +1,61 @@ +```java +import java.util.*; +import java.io.*; + +public class boj21924 { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static StringTokenizer st; + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} + static int nextInt() {return Integer.parseInt(st.nextToken());} + + static int N, M, cnt = 0; + static long answer; + static ArrayList> graph = new ArrayList<>(); + static boolean[] visited; + public static void main(String[] args) throws Exception { + nextLine(); + N = nextInt(); + M = nextInt(); + visited = new boolean[N+1]; + for (int i = 0; i <= N; i++) graph.add(new ArrayList()); + for (int i = 0; i < M; i++) { + nextLine(); + int a = nextInt(); + int b = nextInt(); + int c = nextInt(); + graph.get(a).add(new Node(b, c)); + graph.get(b).add(new Node(a, c)); + answer += c; + } + dijkstra(); + + if (cnt == N) System.out.println(answer); + else System.out.println(-1); + } + + static void dijkstra() { + PriorityQueue pq = new PriorityQueue<>((o1,o2) -> o1.c-o2.c); + pq.offer(new Node(1, 0)); + + while(!pq.isEmpty()) { + Node cur = pq.poll(); + if (visited[cur.v]) continue; + visited[cur.v] = true; + answer -= cur.c; + cnt++; + for (Node next : graph.get(cur.v)) { + if (visited[next.v]) continue; + pq.offer(next); + } + } + } + + static class Node { + int v, c; + public Node(int v, int c) { + this.v = v; + this.c = c; + } + } +} +```