From e802f9bab1f8329b27ff85a3f174c9e7265731a4 Mon Sep 17 00:00:00 2001 From: Jinyeong Seol Date: Tue, 17 Jun 2025 08:54:35 +0900 Subject: [PATCH] =?UTF-8?q?[20250617]=20BOJ=20/=20G4=20/=20=ED=8A=B8?= =?UTF-8?q?=EB=A6=AC=EC=9D=98=20=EC=A7=80=EB=A6=84=20/=20=EC=84=A4?= =?UTF-8?q?=EC=A7=84=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\354\235\230 \354\247\200\353\246\204.md" | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 "Seol-JY/202506/17 BOJ G4 \355\212\270\353\246\254\354\235\230 \354\247\200\353\246\204.md" diff --git "a/Seol-JY/202506/17 BOJ G4 \355\212\270\353\246\254\354\235\230 \354\247\200\353\246\204.md" "b/Seol-JY/202506/17 BOJ G4 \355\212\270\353\246\254\354\235\230 \354\247\200\353\246\204.md" new file mode 100644 index 00000000..4b87a4a7 --- /dev/null +++ "b/Seol-JY/202506/17 BOJ G4 \355\212\270\353\246\254\354\235\230 \354\247\200\353\246\204.md" @@ -0,0 +1,73 @@ +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class Main { + private static int N; + private static List[] graph; + private static boolean[] visited; + private static int maxDistance; + private static int farthestNode; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + N = Integer.parseInt(br.readLine()); + graph = new List[N + 1]; + + for (int i = 1; i <= N; i++) { + graph[i] = new ArrayList<>(); + } + + for (int i = 0; i < N - 1; i++) { + st = new StringTokenizer(br.readLine()); + + int parent = Integer.parseInt(st.nextToken()); + int child = Integer.parseInt(st.nextToken()); + int weight = Integer.parseInt(st.nextToken()); + + graph[parent].add(new Node(child, weight)); + graph[child].add(new Node(parent, weight)); + } + + visited = new boolean[N + 1]; + maxDistance = 0; + farthestNode = 1; + dfs(1, 0); + + visited = new boolean[N + 1]; + maxDistance = 0; + dfs(farthestNode, 0); + + System.out.println(maxDistance); + } + + private static void dfs(int node, int distance) { + visited[node] = true; + + if (distance > maxDistance) { + maxDistance = distance; + farthestNode = node; + } + + for (Node next : graph[node]) { + if (!visited[next.to]) { + dfs(next.to, distance + next.weight); + } + } + } + + static class Node { + int to; + int weight; + + Node(int to, int weight) { + this.to = to; + this.weight = weight; + } + } +} +```